How To: WCF Serialization Using Both XmlSerializerFormat and DataContractSerializer

On one of my projects, we’ve recently decided to switch from a SOAP-based interface for our SDK to a REST-based interface.  One potential problem: we can’t break the old SOAP interface.

Ideally, we’d be able to use the same underlying business objects for both access paths, but we were unsure how well WCF’s DataContractSerializer and XMLSerializerFormat would play together.  Our existing SOAP interface made heavy usage of the DataContractSerializer; I know we could have used that for the REST interfaces as well, but we needed to support XML attributes to align and integrate with other internal projects.

It turns out that you can mock up the business objects with attributes for both DataContractSerializer and XmlSerializerFormat, but the interfaces that expose these objects must be different.  So you can’t have, say, an IDataService that functions for both a DataContract interface and an Xml interface.  The attributes annotating the interface methods must be distinct, otherwise the DataContractSerializer will usurp the XmlSerializerFormat.


[ServiceContract]
[DataContractFormat]
public interface IDataService
{
  [OperationContract]
  List<MyObject> GetMyObjects();
}

[ServiceContract]
[XmlSerializerFormat]
public interface IDataService2
{
  [WebGet(UriTemplate="")]
  List<MyObject> GetMyObjects();
}

[DataContract]
[XmlRoot("myObject")]
public class MyObject
{
  [DataElement]
  [XmlAttribute("name")]
  public String Name { get; set; }
}

This may be not be ideal because now we have two interfaces. So, an alternative is to change to a single interface and pushing the attribute annotations to the implementations. That looks more like this:


public interface IDataService
{
  List<MyObject> GetMyObjects();
}

[ServiceContract]
[XmlSerializerFormat]
public class RestDataService : IDataService
{
  [WebGet(UriTemplate("")]
  public List<MyObject> GetMyObjects() 
  {
    return new List<MyObject>();
  }
}
 
[ServiceContract]
[DataContractFormat]
public class SoapDataService : IDataService
{
  [OperationContract]
  public List<MyObject> GetMyObjects()
  {
    return new List<MyObject>();
  }
}

6 Responses to How To: WCF Serialization Using Both XmlSerializerFormat and DataContractSerializer

  1. Wow this is a great resource.. I’m enjoying it.. good article

  2. Great information! I’ve been looking for something like this for a while now. Thanks!

  3. nice post. thanks.

  4. awesome blog, do you have twitter or facebook? i will bookmark this page thanks

  5. I really like your blog and i really appreciate the excellent quality content you are posting here for free for your online readers. thanks peace klara.

  6. wohh just what I was searching for, thanks for posting .