Monday, 18 March 2013

What is the purpose of ExtensionDataObject in WCF? or How to make DataContract forward compatible?

     A .NET serialization system supports backward-compatibility on custom data types naturally. However, sometimes we also need forward-compatibility for data types used in a WCF service. Suppose that you have a service that exchanges some custom data types between clients. If one side updates the custom data type (adds some fields or properties) or uses a newer version, it is important to make sure that the other side  can still work correctly with the updated data type instances without using the updated version of data.

                Let see how can we achieve this in WCF.

  1.First we need to make our Custom Data type to implement the IExtensibleDataObject interface.
[DataContract]

public class Employee: IExtensibleDataObject
{
[DataMember]
public string Name{ get; set; } [DataMember]
public string Address{ get; set; }

public ExtensionDataObject ExtensionData
{
get;
set;
}
}
 

2.   Next we need to make sure that we  haven't enabled the IgnoreExtensionDataObject property on ServiceBehaviorAttribute applied on your WCF service .This property is disabled by default.

 After the DataContract type implements the IExtensibleDataObject interface, an ExtensionDataObject property is added; this property plays an important role in forward-compatible serialization. WCF will use DataContractSerializer for DataContract type serialization/deserialization. When DataContractSerializer finds that a certain type (used for operation parameters or return value) has implemented the IExtensibleDataObject interface, it will store any data (this is obtained from the message stream during deserialization) that doesn't have corresponding property/fields in the type definition into the ExtensionDataObject property so that these data will not get lost. And if the deserialized instance (with some unknown data stored in ExtensionDataObject)is serialized into the message later, DataContractSerializer will write out ExtensionDataObject into the message stream again. This ensures that the data in the new version of DataContract can be consumed by the service/client with the old type definition correctly, instead of raising unexpected type, mismatching, or serialization exceptions

The following modified data type can be consumed by the service/client that has the old definition, as explained earlier, without synchronizing the DataContract type definition:

[DataContract]
public class Employee: IExtensibleDataObject
{
[DataMember]
public string Name{ get; set; } [DataMember]
public string Address{ get; set; }
[DataMember]
public string Designation{ get; set; }

public ExtensionDataObject ExtensionData
{            get; set;       }
}
 

 


No comments:

Post a Comment