Abhi's .Net

– Abhishek D V

ServiceKnownType and KnownType attribute in WCF

Leave a comment

In this articles we will discuss about significance of ServiceKnownType and KnownType attribute in WCF.

Lets look at an example to understand this:

  1. [ServiceContract]
  2.     public interface IService
  3.     {
  4.         [OperationContract]
  5.         void AddVehicle( Vehicle v );
  6.     }

 

  1. [DataContract]
  2.     public class Vehicle
  3.     {
  4.         [DataMember]
  5.         public string VehicleName { get; set; }
  6.         [DataMember]
  7.         public int VehicleModel { get; set; }
  8.     }
  9.  
  10.     [DataContract]
  11.     public class Car : Vehicle
  12.     {
  13.         [DataMember]
  14.         public bool IsHatchBack { get; set; }
  15.     }

 

In the above example we see a a servicecontract which adds vehicle and takes vehicle as a parameter and looking at the datacontracts we have a class called Car inherited from Vehicle.

Now on referencing this service at client side we expect to see Car class generated at client’s proxy but NO client proxy will not be able to generate car class, Since Car is not part of contract DataContractSerializer fails to serialize.

To solve this problem decorate the method or contract with ServiceKnownType attribute as shown below:

  1. [ServiceContract]
  2.     public interface IService
  3.     {
  4.         [OperationContract]
  5.         [ServiceKnownType(typeof(Car))]
  6.         void AddVehicle( Vehicle v );
  7.     }

Alternatively we can use KnownType attribute at class level as shown below:

  1.     [DataContract]
  2.     [KnownType(typeof(Car))]
  3.     public class Vehicle
  4.     {
  5.         [DataMember]
  6.         public string VehicleName { get; set; }
  7.         [DataMember]
  8.         public int VehicleModel { get; set; }
  9.     }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s