Tuesday, July 30, 2013

DataContract Serializer and IsReference property

In .net Framework 3.5 SP1, DataContractSerializer supports by-ref object graph serialization by using the standard xsd:ID/xsd:IDREF attributes. 
You can set the IsReference=true on your DataContract definition and serializer will generate XML elements with IDs/IDREFs attributes and will link them together rather embedding them inside each other(default behavior). 
Also if you examine the XSD generated by WCF as part of the metadata export, it will also contain the standard ID/IDREF xml schema attributes. Because of this, xml can be correctly parsed and understood by any framework in a standard way. 
This change will enable serialization of object graphs having circular references (which wasn’t possible previously – at least not without writing custom code) and will also reduce the size of the serialized xml. 
Let’s examine this change using the following DataContract definition: 
    [DataContract] 
    public class Employee 
    { 
        [DataMember] 
        public string Name { getset; } 
        [DataMember] 
        public Employee Manager { getset; } 
    } 
    [DataContract] 
    public class Department 
    { 
        [DataMember] 
        public List<Employee> Staff { getset; } 
        [DataMember] 
        public string DeptName { getset; } 
    } 
Now if we serialize following Department object using DataContractSerializer 
        var kenny = new Employee() { Name = “Kenny” }; 
        var bob = new Employee() { Name = “Bob”, Manager = kenny }; 
        var alice = new Employee() { Name = “Alice”, Manager = kenny }; 
        var ahmed = new Employee() { Name = “Ahmed”, Manager = kenny }; 
   
        var dept = new Department() { DeptName = “RandD”, Staff = new List<Employee>() { kenny, bob, alice, ahmed } };         
        DataContractSerializer dcs = new DataContractSerializer(typeof(Department));         
        var ms = new MemoryStream(); 
        dcs.WriteObject(ms, dept); 
        ms.Seek(0, SeekOrigin.Begin); 
          
        var sr = new StreamReader(ms); 
        var xml = sr.ReadToEnd(); 
We will get this xml. 
      <DeptName>RandD</DeptName> 
      <Staff> 
            <Employee> 
                  <Manager i:nil=true /> 
                  <Name>Kenny</Name> 
            </Employee> 
            <Employee> 
                  <Manager> 
                        <Manager i:nil=true /> 
                        <Name>Kenny</Name> 
                  </Manager>  
                  <Name>Bob</Name> 
            </Employee> 
            <Employee> 
                  <Manager> 
                        <Manager i:nil=true /> 
                        <Name>Kenny</Name> 
                  </Manager>  
                  <Name>Alice</Name> 
            </Employee> 
            <Employee> 
                  <Manager> 
                        <Manager i:nil=true /> 
                        <Name>Kenny</Name> 
                  </Manager>  
                  <Name>Ahmed</Name> 
            </Employee> 
      </Staff> 
</Department> 
You can see manager Kenny is included in all Employee objects, essentially a by-value inclusion.  Now if we change the declaration of Employee class to following: 
    [DataContract(IsReference = true)] 
    public class Employee 
    { 
         [DataMember] 
        public string Name { getset; } 
        [DataMember] 
        public Employee Manager { getset; } 
    } 
With above change, you will get following different xml. 
      <DeptName>R&D</DeptName> 
      <Staff> 
            <Employee z:Id=i1 xmlns:z=http://schemas.microsoft.com/2003/10/Serialization/> 
                  <Manager i:nil=true />  
                  <Name>Kenny</Name> 
            </Employee> 
            <Employee z:Id=i2 xmlns:z=http://schemas.microsoft.com/2003/10/Serialization/> 
                  <Manager z:Ref=i1 />  
                  <Name>Bob</Name> 
            </Employee> 
            <Employee z:Id=i3 xmlns:z=http://schemas.microsoft.com/2003/10/Serialization/> 
                  <Manager z:Ref=i1 />  
                  <Name>Alice</Name> 
            </Employee> 
            <Employee z:Id=i4 xmlns:z=http://schemas.microsoft.com/2003/10/Serialization/> 
                  <Manager z:Ref=i1 />  
                  <Name>Ahmed</Name> 
            </Employee> 
      </Staff> 
</Department> 
In attribute-free (POCO) world: 
you can use a different ctor, taking a boolean flag, to toggle by-val/by-ref serialization. 
      DataContractSerializer(Type type, IEnumerable knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate)
To enable circular references for operation or service scope, you can use custom behaviors etc. Essentially you need the ability to hook into serializer instantiation process and create the instance using above overload: 
   1. Subclass DataContractSerializerOperationBehavior 
   2. Ovverride CreateSerializer method 
   3. Create a new DCS instance passing true to preserveObjectReferences param. 
class DataContractSerializerOperationBehaviorEx : DataContractSerializerOperationBehavior 
public DataContractSerializerOperationBehaviorEx(OperationDescription operation):base(operation) 
public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes) 
return new DataContractSerializer(type, name, ns, knownTypes, this.MaxItemsInObjectGraph, this.IgnoreExtensionDataObject, truethis.DataContractSurrogate); 
public override XmlObjectSerializer CreateSerializer(Type type, System.Xml.XmlDictionaryString name, System.Xml.XmlDictionaryString ns, IList<Type> knownTypes) 
return new DataContractSerializer(type, name, ns, knownTypes, this.MaxItemsInObjectGraph, this.IgnoreExtensionDataObject, truethis.DataContractSurrogate); 
}

No comments:

Post a Comment