Friday, December 10, 2010

WCF: TypedMessageConverter and its default serializer

At some point you may face a need to create a Message from your MessageContract.
The helper class for this is TypedMessageConverter with possible usage as:

TypedMessageConverter converter = TypedMessageConverter.Create(
 typeof(getServiceStatusResponse1), "", "YourDefaultNamespace")
Message reply = converter.ToMessage(…..

Next second, when looking at the message generated, you may see quite odd looking result with all the backing fields exposed instead of your properties and set off namespaces. What’s the heck???

If we look behind one of create overloads:

public static TypedMessageConverter Create(Type messageContract, string action) {
    return Create(messageContract, action, null, 

Where TypeLoader has the following DefaultDataContractAttribute:

internal static DataContractFormatAttribute DefaultDataContractFormatAttribute;

This in turn commands it to use a DataContractSerializer and screw Yours very carefully designed XmlType/Element etc annotations.

The cure is very simple, create a typed converter with XmlSerializerFormatAttribute:

TypedMessageConverter converter = TypedMessageConverter.Create(typeof(getServiceStatusResponse1),
 "", "YourDefaultNamespace", new XmlSerializerFormatAttribute() ); 

And feel the joy of Your perfectly looking Message!

[Update 1-Apr-2011, you can read to avoid possible memory leaks when you use TypedMessageConverter with XmlSerializer]

No comments: