Thursday, September 22, 2011

WCF Extensibility – Data Contract Resolver

This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.

Continuing on serialization, this post is about a new feature on the WCF serializers in .NET Framework 4.0, the DataContractResolver. Like the previous post on surrogates, there is already good documentation on MSDN, so this post will be short. But since I’ve seen an issue this week on the forums, I thought it’d be worth including the code here in this series.

In order to understand the data contract resolver, we need to take a step back and look at a common issue (and source of confusion) in WCF: known types. In order for WCF to be able to serialize or deserialize an object graph, it needs to know about all the objects in that graph. If the actual type of the object is the same as its declared type, then WCF already knows about it (the “baseInstance” member in the code below). If those types are different, then WCF doesn’t know by default about the type – in the case of the “derivedInstance” in the code below, WCF doesn’t know the MyDerived type, so it won’t serialize it unless we tell it that this type is known.

    public class MyBase { }
    public class MyDerived : MyBase { }
    public class MyType
        public MyBase baseInstance = new MyBase();
        public MyBase derivedInstance = new MyDerived();

There are many good descriptions on why we need the known types and how to set them (“official” MSDN documentation, Youssef Moussaoui’s MSDN blog, Mark Gravell’s Stack Overflow post, Richard Blewett’s blog, etc.) so I won’t go in detail here. But known types serves a purpose that we can declare, when the serialize is being created, which types are to be considered "valid” even though they’re not part of the object declaration. And the part in italic is important here – once the known type list is passed somehow to the serializer, it’s set and it cannot be changed during the serializer lifetime.

Read more: Carlos' blog
QR: wcf-extensibility-data-contract-resolver.aspx

Posted via email from Jasper-Net