WCF Extensibility – Serialization Surrogates
This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.
After the callbacks, the next extensibility point on the list for serialization are the surrogates. This will be a short post, since the surrogate idea is simple (once you understand it) and there is some good documentation on MSDN about this issue, so I don’t think I need to repeat it here.
Surrogates have been around for a while, even before WCF, and their idea is simple: replacing one type A which is part of an object graph to be serialized with another type B (the “surrogate”). The main reasons why we’d want to do that are either because the type A isn’t serializable at all, or because it doesn’t have a serialization format which we want, so we use a surrogate to change it. The first case is straightforward – sometimes you have a type from a 3rd party or a legacy library which cannot be modified to accommodate serialization, but it’s part of the object graph which you want to exchange between client and server. One possible solution is to replicate the graph in Data Transfer Objects (DTO) which only contain the data which needs to be serialized. Sometimes, however, this may not be the best approach (too many types, high cost to convert between DTOs and objects with business logic, etc.), so a surrogate can be an way out. The second case (wanting to change the serialization format) doesn’t happen very often, but there are some scenarios where users want to change the way a type is serialized.
Before WCF was released, the way to implement surrogates was by using the ISurrogateSelector and ISerializationSurrogate interfaces.. Most of the previous “serializers” (including the BinaryFormatter and the SoapFormatter) supported it via the IFormatter interface. When the formatters were serializing an object graph, they’d search in their “surrogate chain” to see if any surrogate was present to deal with each type in the graph; if this was the case, then it would use the surrogate to serialize / deserialize the objects instead of the object itself.
With WCF, and the notion of a data contract, those surrogates could still be used without problems during runtime, but their contract didn’t specify how the data would be serialized (it’s just some code being executed after all), so the whole notion of a shared contract cannot really be enforced using the traditional surrogacy. Enter the new interface, IDataContractSurrogate, which, besides the ability to replace one type with another for serialization during runtime, also contains additional methods which are invoked during type export and import (when the contract is being exposed in the metadata to be consumed by tools such as svcutil.exe or Add Service Reference, or when those tools are being used to create a service proxy). This new surrogate interface is supported by both the DataContractSerializer and the DataContractJsonSerializer (although as far as I know for the latter the import / export methods aren’t called) – the NetDataContractSerializer implements the IFormatter interface, so it supports the “old-style” surrogacy, and the XmlSerializer doesn’t have support for surrogates.
Interface definition
- public interface IDataContractSurrogate
- {
- object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType);
- object GetCustomDataToExport(Type clrType, Type dataContractType);
- Type GetDataContractType(Type type);
- object GetDeserializedObject(object obj, Type targetType);
- void GetKnownCustomDataTypes(Collection<Type> customDataTypes);
- object GetObjectToSerialize(object obj, Type targetType);
- Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData);
- CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit);
- }
As I mentioned, the IDataContractSurrogate interface is quite complex, and most implementations don’t use all of its methods. The main ones (the ones which are implemented in the majority of uses) are the ones called in the runtime (serialization and deserialization): GetDataContractType (given a type in the original data contract, return a possible surrogate type which can be used in place of it), GetObjectToSerialize (during serialization, can be used to replace one object with another) and GetDeserializedObject (during deserialization, does the opposite of GetObjectToDeserialize). The MSDN article about data contract surrogates has a more thorough description of all the methods, so I’ll just leave the link here instead of repeating what is already there.
How to use a data contract surrogate
When creating the WCF serializers (both the DataContractSerializer and the DataContractJsonSerializer) you can use one of their constructor overloads which take an IDataContractSurrogate parameter, so this is straightforward. The example below shows one non-serializable type which is part of an object graph (NonSerializablePerson isn’t serializable because it’s not decorated with any attributes, and does not have a parameter-less constructor). The surrogate is used to replace it with another type, and when it’s deserialized, the surrogate does the opposite, recreating the original type from the replacement one.
- public class NonSerializablePerson
- {
- public string Name { get; private set; }
- public int Age { get; private set; }
- public NonSerializablePerson(string name, int age)
- {
- this.Name = name;
- this.Age = age;
- }
- public override string ToString()
- {
- return string.Format("Person[Name={0},Age={1}]", this.Name, this.Age);
- }
- }
- public class Family
- {
- public NonSerializablePerson[] Members;
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.AppendLine("Family members:");
- foreach (var member in this.Members)
- {
- sb.AppendLine(" " + member);
- }
- return sb.ToString();
- }
- }
- [DataContract]
- public class PersonReplacement
- {
- [DataMember(Name = "PersonName")]
- public string Name { get; set; }
- [DataMember(Name = "PersonAge")]
- public int Age { get; set; }
- }
- public class MyPersonSurrogate : IDataContractSurrogate
- {
- public Type GetDataContractType(Type type)
- {
- if (type == typeof(NonSerializablePerson))
- {
- return typeof(PersonReplacement);
- }
- else
- {
- return type;
- }
- }
- public object GetDeserializedObject(object obj, Type targetType)
- {
- if (obj is PersonReplacement)
- {
- PersonReplacement person = (PersonReplacement)obj;
- return new NonSerializablePerson(person.Name, person.Age);
- }
- return obj;
- }
- public object GetObjectToSerialize(object obj, Type targetType)
- {
- if (obj is NonSerializablePerson)
- {
- NonSerializablePerson nsp = (NonSerializablePerson)obj;
- PersonReplacement serializablePerson = new PersonReplacement
- {
- Name = nsp.Name,
- Age = nsp.Age,
- };
- return serializablePerson;
- }
- return obj;
- }
- public void GetKnownCustomDataTypes(Collection<Type> customDataTypes)
- {
- throw new NotSupportedException("unused");
- }
- public object GetCustomDataToExport(Type clrType, Type dataContractType)
- {
- throw new NotSupportedException("unused");
- }
- public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType)
- {
- throw new NotSupportedException("unused");
- }
- public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData)
- {
- throw new NotSupportedException("unused");
- }
- public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit)
- {
- throw new NotSupportedException("unused");
- }
- }
- class SurrogatesTest
- {
- public static void Test()
- {
- DataContractSerializer dcs = new DataContractSerializer(typeof(Family), null, int.MaxValue, false, false, new MyPersonSurrogate());
- MemoryStream ms = new MemoryStream();
- Family myFamily = new Family
- {
- Members = new NonSerializablePerson[]
- {
- new NonSerializablePerson("John", 34),
- new NonSerializablePerson("Jane", 32),
- new NonSerializablePerson("Bob", 5),
- }
- };
- dcs.WriteObject(ms, myFamily);
- Console.WriteLine("Serialized: {0}", Encoding.UTF8.GetString(ms.ToArray()));
- ms.Position = 0;
- object newFamily = dcs.ReadObject(ms);
- Console.WriteLine("Deserialized:");
- Console.WriteLine(newFamily);
- }
- }
What about surrogates using within the context of WCF services? One possible way is to replace the serializer used in WCF, which involves replacing the DataContractSerializerOperationBehavior. That surely works, but using surrogates is something simple enough that WCF added a property to that behavior itself, so it doesn’t need to be replaced with a custom class. In the example below, we use the same Family type in a service, but we set the DataContractSurrogate property to our surrogate. Notice that we need to do it on both the server and the client, otherwise when the server (or the proxy) is being opened an exception would be thrown.
- [ServiceContract]
- public interface IFamilyManager
- {
- [OperationContract]
- void AddMember(string name, int age);
- [OperationContract]
- Family GetFamily();
- }
- public class FamilyService : IFamilyManager
- {
- static List<NonSerializablePerson> members = new List<NonSerializablePerson>();
- public void AddMember(string name, int age)
- {
- members.Add(new NonSerializablePerson(name, age));
- }
- public Family GetFamily()
- {
- return new Family { Members = members.ToArray() };
- }
- }
- class SurrogatesTest
- {
- static void DefineSurrogate(ServiceEndpoint endpoint)
- {
- foreach (var operation in endpoint.Contract.Operations)
- {
- var dcsob = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
- dcsob.DataContractSurrogate = new MyPersonSurrogate();
- }
- }
- public static void Test()
- {
- string baseAddress = "https://" + Environment.MachineName + ":8000/Service";
- var host = new ServiceHost(typeof(FamilyService), new Uri(baseAddress));
- var endpoint = host.AddServiceEndpoint(typeof(IFamilyManager), new BasicHttpBinding(), "");
- host.Open();
- DefineSurrogate(endpoint);
- Console.WriteLine("Host opened");
- var factory = new ChannelFactory<IFamilyManager>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
- DefineSurrogate(factory.Endpoint);
- var proxy = factory.CreateChannel();
- proxy.AddMember("John", 34);
- proxy.AddMember("Jane", 32);
- Console.WriteLine(proxy.GetFamily());
- ((IClientChannel)proxy).Close();
- factory.Close();
- Console.Write("Press ENTER to close the host");
- Console.ReadLine();
- host.Close();
- }
- }
One more comment: for endpoints which take / return JSON data (i.e., the ones which use the DataContractJsonSerializer), we also set the DataContractSurrogate property on the DataContractSerializerOperationBehavior – there’s no DataContractJsonSerializerOperationBehavior (the type name is already too large ).
Final thoughts about data contract surrogates
In the example above we showed how to use a surrogate to serialize a type which isn’t serializable itself, but it doesn’t always have to be this way. It’s perfectly fine to use a surrogate to replace a serializable type, it works just as well. The main exception for this are the types considered as primitives by the serializers . Those types cannot be surrogated (this is a common request). The only workaround which I know is the one I showed in the previous post, using callbacks to convert between the primitive type and the expected output.
Coming up
More serialization extensibility, with the data contract resolver and the extension data object.
Comments
- Anonymous
October 15, 2015
Great article. But what if NonSerializeablePerson is a object array? I have this problem with my application. I tried using KnownTypes as per the documentation but this doesn't work either. Can you not use Surrogates and KnownTypes together?