In this articles we will discuss about significance of ServiceKnownType and KnownType attribute in WCF.
Lets look at an example to understand this:
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- void AddVehicle( Vehicle v );
- }
- [DataContract]
- public class Vehicle
- {
- [DataMember]
- public string VehicleName { get; set; }
- [DataMember]
- public int VehicleModel { get; set; }
- }
- [DataContract]
- public class Car : Vehicle
- {
- [DataMember]
- public bool IsHatchBack { get; set; }
- }
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:
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- [ServiceKnownType(typeof(Car))]
- void AddVehicle( Vehicle v );
- }
Alternatively we can use KnownType attribute at class level as shown below:
- [DataContract]
- [KnownType(typeof(Car))]
- public class Vehicle
- {
- [DataMember]
- public string VehicleName { get; set; }
- [DataMember]
- public int VehicleModel { get; set; }
- }