Making WCF Serializer Work with Circular References
The Problem of Circular References
Recently I had to model a tree-like structure using a variation of the GoF composite design pattern and to pass this class to a WCF service for further processing. The class has circular reference as described by the following drawing: Therefore off I went to naively create my DataContract along the following lines:
Unfortunately at run time I was greeted by the following exception:
Object graph for type 'System.Collections.Generic.List`1[[Node ...]]' contains cycles and cannot be serialized if reference tracking is disabled.
The Solution
Reading around I realized that up until some time ago you had to implement your own DataContractSerializer (see for example this post by Sowmy Srinivasan). Luckily, it turns out that with NET 3.5 SP1 everything is much simpler: you just have to use the IsReference parameter in the DataContract attribute, as follows:
The Catch
For some reason, if you turn on the IsReference attribute,
then you cannot set the IsRequired
attribute to true
on any DataMember
of the DataContract. The reason is somehow explained here.
Leave a Comment