Data Contract topology in WCF 4.0 - DataContractResolver
In WCF 3.x, type resolution was done using the “known types” mechanism. During deserialization, when the serializer encounters an instance that isn’t of the same type as the declared type, it inspects the list of declared “known types” to figure out what type to use.
As the author of the service, you could annotate your types/methods with the [KnownType] or [ServiceKnownType] attributes to define the list of possible substitutions. (in code or config)
Unfortunately, WCF 3.x doesn’t provide an easy way to override the type-mapping algorithm used by DataContractSerializer when performing this type of dynamic type resolution at runtime. This means that it was not possible to implement true polymorphism. It was not easy to make sure the serializer will serialize the correct type in the inheritance tree.
The result was flat data contracts.
Personally I think that flat data contracts are good. It makes services simpler and interoperable but I am not happy that a polymorphic data contract is not possible or very difficult to implement.
I think that the service should be just a facade to the business logic. The actual business entities should not exposed. The data contracts are just flat containers from which the business entities are created.
There are scenarios where the actual business entities should be exposed. In those scenarios we would like to serialize a polymorphic hierarchy of data contracts.
In WCF it is possible and easy using the DataContractResolver.
WCF in .NET 4 provides the abstract DataContractResolver class that you can derive from to implement your own custom type resolution algorithm. Your resolver implementation is provided to the DataContractSerializer instance :
var serializer = new DataContractSerializer(typeof(Object), null, int.MaxValue, false, true, null, new MyDataContractResolver());
The new serializer can be bound to the WCF infra using a custom behavior and you are done.
The new WCF_WF SDK samples has a simple example how to implement such resolver.