This is Day 6 article. If you have not read previous articles, please go through following articles:
- Day 1 - WCF Introduction and Contracts
- Day 2 - WCF Fault Contracts
- Day 3 - WCF Message Exchange Patterns
- Day 4 - WCF DataContract
- Day 5 - WCF Difference between service application and service library
In this article we will discuss serialization in WCF, including the default serializer in WCF and the various kinds of serializers that WCF supports.
WCF provides a message-oriented programming framework. We use WCF to transmit messages between applications. Internally WCF represents all the messages by a Message class. When WCF transmits a message it takes a logical message object and encodes it into a sequence of bytes. After that WCF reads those bytes and decodes them in a logical object. The process forms a sequence of bytes into a logical object; this is called an encoding process. At runtime when WCF receives the logical message, it transforms them back into corresponding .Net objects. This process is called serialization.
WCF supports three basic serializers:
WCF deserializes WCF messages into .Net objects and serializes .Net objects into WCF messages. WCF provides DataContractSerializer by default with a servicecontract. We can change this default serializer to a custom serializer like XMLSerializer.
public interface IService1
void AddAuthor(Author author);
The XmlSerializerFormat attribute above the ServiceContract means this serializer is for all operation contracts. You can also set a separate contract for each operation.
Each serializer calls different algorithms for mapping between .Net object and WCF messages. And each serializer produces a slightly different message.
We can use SvcUtil.exe to move between .Net types and XSD. We can export an XSD that describes what the serializer expects and can import an XSD to product types for a specific serializer.
We can find XMLSerializer in the System.Xml.Serialization namespace. WCF supports this serialization from .Net 1.0. It is used by default with the ASP.Net webservices (ASMX).
NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements IFormatter and it is compatible with [Serializable] types. It is not recommended for service oriented design.
DataContractSerializer is a default serializer for WCF. We need not to mention DataContractSerializer attribute above the service contract.
In my next article we will see step-by-step implementation of DataContractSerializer and code demonstration.