Using DataContractSerializer and DataContractResolver to Provide the Functionality of NetDataContractSerializer
The NetDcSasDcSwithDCR sample demonstrates how the use of DataContractSerializer with an appropriate DataContractResolver provides the same functionality as NetDataContractSerializer. This sample shows how to create the appropriate DataContractResolver and how to add it to the DataContractSerializer.
Sample details
NetDataContractSerializer differs from DataContractSerializer in one important way: NetDataContractSerializer includes CLR type information in the serialized XML, whereas DataContractSerializer does not. Therefore, NetDataContractSerializer can be used only if both the serializing and deserializing ends share the same CLR types. However, it is recommended to use DataContractSerializer because its performance is better than NetDataContractSerializer. You can change the information that is serialized in DataContractSerializer by adding a DataContractResolver to it.
This sample consists of two projects. The first project uses NetDataContractSerializer to serialize an object. The second project uses DataContractSerializer with a DataContractResolver to provide the same functionality as the first project.
The following code example shows the implementation of a custom DataContractResolver named MyDataContractResolver
that is added to the DataContractSerializer in the DCSwithDCR project.
class MyDataContractResolver : DataContractResolver
{
private XmlDictionary dictionary = new XmlDictionary();
public MyDataContractResolver()
{
}
// Used at deserialization
// Allows users to map xsi:type name to any Type
public override Type ResolveName(string typeName, string typeNamespace, DataContractResolver knownTypeResolver)
{
Type type = knownTypeResolver.ResolveName(typeName, typeNamespace, null);
type ??= Type.GetType(typeName + ", " + typeNamespace);
return type;
}
// Used at serialization
// Maps any Type to a new xsi:type representation
public override void ResolveType(Type dataContractType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
{
knownTypeResolver.ResolveType(dataContractType, null, out typeName, out typeNamespace);
if (typeName == null || typeNamespace == null)
{
XmlDictionary dictionary = new XmlDictionary();
typeName = dictionary.Add(dataContractType.FullName);
typeNamespace = dictionary.Add(dataContractType.Assembly.FullName);
}
}
}
To use this sample
Using Visual Studio, open the DCRSample.sln solution file.
Right-click the solution file and choose Properties.
In the Solution Property Pages dialog, under Common Properties, Startup Project, select Multiple startup projects:.
Next to the DCSwithDCR project, select Start from the Action dropdown.
Next to the NetDCS project, select Start from the Action dropdown.
Click OK to close the dialog.
To build the solution, press Ctrl+Shift+B.
To run the solution, press Ctrl+F5.