Re: Serialization and Encoding Serializing and Encoding
Windows Communication Foundation supports three serializers: XmlSerializer, DataContractSerializer, and NetDataContractSerializer. Each of these comes with different mapping algorithms and customization techniques. (See Figure 1 for a comparison.) Nevertheless, each performs the same fundamental task—mapping between .NET objects and XML Infosets.
DataContractSerializer is the default and is always used unless specified otherwise. You can choose a different serializer by annotating the service contract with an attribute, as shown here:
[XmlSerializerFormat]
[ServiceContract]
public interface IEchoService
{
[DataContractFormat]
[OperationContract]
Person EchoPerson(Person person);
[OperationContract]
Address EchoAddress(Address address);
[OperationContract]
Phone EchoPhone(Phone phone);
}
n this example, [XmlSerializerFormat] specifies XmlSerializer as the default serializer for all methods on the contract. However, I've overridden the serializer on EchoPerson by annotating the method with [DataContractFormat]. There isn't an attribute for NetDataContractSerializer, but you can write a custom attribute to apply it in the same way as the others if needed. The serializer is considered part of the service contract because it directly impacts your code.
Windows Communication Foundation also lets you specify the encoding to be used. Whereas serialization defines how .NET objects map to XML Infosets, the encoding defines how the XML Infoset is written out to a stream of bytes. Windows Communication Foundation currently supports the following encodings: text, binary, and Message Transmission Optimization Mechanism (MTOM). However, more encodings, including your own custom encodings, could be added down the road.
If you use each of the three encodings to write out the same XML Infoset, you'll get three very different byte streams, but they'll all represent the same logical data. The encoding isn't considered part of the service contract, but rather a configuration detail since it doesn't impact your code—you control the encoding by configuring the endpoint's binding.
The separation of serialization from encoding makes it possible to build your applications on a consistent data model (the XML Infoset) while providing flexibility in representation (the encoding). This is a key feature when applying Windows Communication Foundation to a variety of real-world scenarios. If you care about interoperability, you can choose to use the text encoding. When performance is more of a concern, you can choose to use the binary encoding. In either case, the encoding choice is decoupled from the serialization mechanism. |