Using the XmlSerializer as an XmlObjectSerializer with WCF



The Windows Communication Foundation introduced the new DataContractSerializer to replace the XmlSerializer in many scenarios.  The DataContractSerializer is faster than the XmlSerializer, but has certain limitations.  For example it does not support serializing an object’s members as XML attributes.  When you write a WCF client that calls a service, WCF will generate a proxy class that defaults to using the DataContractSerializer and falls back to the XmlSerializer if the service uses features that the DataContractSerializer does not support.  This fallback mechanism is automatic if you’re using WCF’s service model.

But if you’re working at WCF’s messaging layer, you must explicitly choose which serializer to use.  You can use any serializer that derives from System.Runtime.Serialization.XmlObjectSerializerSystem.Runtime.Serialization.DataContractSerializer already derives from this class — but System.Xml.Serialization.XmlSerializer does not.  So you have some work to do before you can use the XmlSerializer as your serializer of choice at the messaging layer of WCF.

In order to use the XmlSerializer to send messages with WCF, we have to define a class that derives from XmlObjectSerializer and uses the XmlSerializer internally.  In essence we will create a wrapper class for the XmlSerializer that makes it look and work like an XmlObjectSerializer.  XmlObjectSerializer is an abstract class with only a few methods we need to implement.

Below is a sample of a class that will do just that.

Andrew Arnott

Principal Software Engineer, Visual Studio Platform

Follow Andrew   


Leave a comment