Serializing Object Graphs
How do I write out an object that contains a reference to itself?
Using the default options with the standard serializer for data contracts gives you a configuration where object references are replaced by an actual instance of the object being referenced. In essence, the data contract serializer expands object references into copies of the original object. Implementing object references by making a copy solves one of the problems of contract-based data transfer- describing an object reference requires a description language that is a level abstracted from the user-controlled description of the data contents. After all, there are some pretty flexible description languages, like XML, that don't include object references in their minimal, core definitions.
Implementing object references by making a copy also creates a problem for data transfer- every time we want to insert a reference to an object, we have to make a whole new copy of that object. For some cases, that is simply wasteful. For other cases, such as circular object references, a copy-on-reference policy is entirely unworkable. The copy approach leads to an object graph of infinite size whereas the reference approach leads to an object graph of finite size. Clearly, that is a situation where we would prefer implementing object references with object references despite the other consequences.
WCF supports both copying and preserving object references. The default data contract serializer uses copies to implement object references. If you want to use object references to implement object references, then you can toggle the PreserveObjectReferences setting when creating the serializer to enable this behavior. Each serializer is free to solve this problem in its own way. For example, although DataContractSerializer defaults to copying references, the NetDataContractSerializer defaults to preserving references.
Next time: Replacing the Serializer
Comments
Anonymous
May 14, 2007
A nice sample of serializing object graphs can be found here: http://blogs.microsoft.co.il/blogs/bursteg/archive/2006/08/10/WCF-Serialization-Same-Objects.aspxAnonymous
May 14, 2007
How do I control the generation of XML processing instructions during serialization? XML processing instructionsAnonymous
May 14, 2007
I posted details on handling circular references in object graphs in WCF on my blog a few months back. Details can be found here for the curious: http://www.jameskovacs.com/blog/GoingAroundInCirclesWithWCF.aspx