I have a fair amount of experience with the DataContractSerializer and handling custom type serialization using IDataContractSurrogate. Today, I have learned about the new DataContractResolver in .NET 4.0 which seems to provider a similar and more loosely coupled implementation of IDataContractSurrogate.
The problem I have is that I need to supply some custom de/serialization behavior that gets used by a call to Message.GetBody().
The Message payload in question has (among other things) an public read/write property that returns "object". Contrived example:
public class MessageContents
{
public int SomeValue { get; set; }
public object SomeData { get; set; }
}
...
MessageContents entity = new MessageContents { SomeValue = 1, SomeData = new Whatever() };
Message entityMessage = Message.CreateMessage(
MessageVersion.Soap12WSAddressing10,
String.Format("{0}Request", operation),
entity);
...
entityMessage.GetBody<MessageContents>()
The GetBody<>() call throws the normal "can't deserialized unrecognized type 'Whatever'" expection. When using the DataContractSerializer directly, I've had no problem solving the problem, but since GetBody<>() uses its own DataContractSerializer, how can I affect this deserialization behavior?
The reason I'm dealing with Messages directly is because the service interface in question is returning large amounts of streaming data and WCF requires me to form my operation contract with Message types.
I've tried adding a DataContractSerializerOperationBehavior behavior to my service interface (for each operation), but the registered DataContractResolver is never getting fired.
Anyone have any suggestions?
You could use the Message.GetBody<T>(XmlObjectSerializer) method and pass a properly configured instance of the DataContractSerializer class:
var knownTypes = new string[] { "Whatever" };
var serializer = new DataContractSerializer(typeof(MessageContents), knownTypes);
MessageContents contents = message.GetBody<MessageContents>(serializer);
Related resources: