Fixing WCF Circular Reference Serialization

February 3, 2009 14:03 by wjchristenson2

As a WCF developer, you may (or soon will) run into problems when an object is referenced multiple times within the business objects being serialized.  Let’s say we have a parent object which has a collection of children.  Therefore we have one-to-many children for a parent.  Let’s say we want a property for each child which references its parent.  When the DataContractSerializer attempts to serialize the parent and children, you’ll soon discover that the cyclic relationship between the parent and its children and back to the parent will cause a stack overflow.  Below is a basic diagram that shows a basic parent to child – child to parent object (cyclic) relationship where this can occur.

I’ve seen a lot of workarounds to this problem and most involve writing your own serializers.  In .NET 3.5 SP1, we can now specify an IsReference parameter in the DataContract attribute which will automatically retain our cyclic object relationships for us.  Specify this for objects which are referenced in other objects.  In our example, the parent would be a reference because the child object references it.  The child object would not be a reference because the children property is a collection of child.  Simple solution compared to what WCF developers had to do in the past.  Here’s a sample of a class definition that is of a reference type:


   1:      <DataContract(IsReference:=True)> _
   2:      Public Class Parent