.NET Serializers, part 2
There were some things left (well, a lot, actually) from my previous article on .NET serializers. One of these things was the ability to have serializers call specific methods before or after serialization. This can be achieved in two ways:
-
Through implementation of interfaces;
-
Through the use of attributes.
Interface System.Runtime.Serialization.IDeserializationCallback defines a method named OnDeserialization that is called after de deserialization process. You receive the deserialized object as its only argument and you can change it at your will. Only works with IFormatter-based serializers, such as BinaryFormatter and SoapFormatter, not with XmlSerializer.
As for attributes, the following can be applied to methods of your class:
-
System.Runtime.Serialization.OnSerializingAttribute (IFormatter and XmlObjectSerializer)
-
System.Runtime.Serialization.OnSerializedAttribute (IFormatter and XmlObjectSerializer)
-
System.Runtime.Serialization.OnDeserializingAttribute (IFormatter and XmlObjectSerializer)
-
System.Runtime.Serialization.OnDeserializedAttribute (IFormatter and XmlObjectSerializer)
Doesn't matter if the methods are public or private, but they must have the following signature:
void
MethodName(StreamingContext ctx)
Through the StreamingContext parameter you can access the properties that will be serialized or deserialized and act upon them.
Please notice that the attribute-based approach is the only one that works with WCF, which uses XmlObjectSerializer-based serializers, as well as IFormatter-based.