Friday, May 5, 2017

Four Different ways to use knowntype attribute

Data Contract -: 

Data Contract attribute is used for the type of data that will be sent/received between a service and a client. Some time data is not know to client an example is derived type, in that case there will be some problem in De-Serialization. De-Serialization engine could not recognize the derived data contract and will threw error.
  • Global Level
    • Using Code at base type
    • Using Web.config
  • Service Contract Level
  • Operation Contract Level


Global using Code


[KnownType(typeof(Santro))]
[KnownType(typeof(Maruti))]
[DataContract]
public class Car
{
}
[DataContract]
public class Santro : Car
{

[OperationContract]
void GetModal( );
}
[DataContract]
public class Maruti : Car
{
[OperationContract]
void GetModal( );
}

using on base type it is applicable for all functions.

Global Level using config


<system.runtime.serialization>
     <dataContractSerializer>
                  <declaredTypes>
                             MyService.Car, 
                                                MyService, Version=, 
                                                Culture=Neutral, PublicKeyToken=null”>
                                         <knownType type=”MyService.Santro, 
                                                MyService, Version=<version here>, 
                                                Culture=Neutral, PublicKeyToken=null” />
                                         <knownType type=”MyService.Maruti, 
                                                MyService, Version=<version here>, 
                                                Culture=Neutral, PublicKeyToken=null” />
                            </add>
                  </declaredTypes>
     </dataContractSerializer>
</system.runtime.serialization>


Service Contract 


[ServiceKnownType(typeof(Car))]
[ServiceKnownType(typeof(Truck))]
[ServiceContract]
public Interface ICarService
{
[OperationContract]
Vehicle AddNewCar(Car car);

[OperationContract]
bool UpdateCar(Car car);
}
will  be applicable for all functioned declared within this interface but not for other interfaces.


Operation Contract Level


[ServiceContract]
public Interface ICarService
{
      [ServiceKnownType(typeof(Santro))]
      [ServiceKnownType(typeof(Maruti))]
      [OperationContract]
      Vehicle AddNewCar(Car car);
      [OperationContract]
      bool UpdateCar(Car car);  
}

will be applicable only for contract on which ServiceKnownType is defined.

No comments:

Followers

Link