1

I've recently been exposed to some code which consistently uses Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract.getSerializer(typeof(X)) to create a new serializer, where X is the type of object being deserialized. When looking up documentation, most documentation would use new XmlSerializer(typeof(X)), and I could hardly find any documentation on XmlSerializerContract (and the only official documentation I did find pertained to Outlook).

What are the benefits to using Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract.getSerializer() versus new XmlSerializer()? Under what scenarios would I want to use each?

1 Answer 1

3

For performance optimization, XmlSerializer (and XmlSerializerFactory) generate temporary assembly containing serializer for particular types. The type that you have mentioned (Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializerContract) are from these generated assemblies (see http://treyhutcheson.wordpress.com/2007/02/20/dynamic-interface-implementations/) - so it's quite natural that you haven't found any documentation for the same.

Frankly, to me it seems to be some hack solution probably to work-around memory leak issues related XmlSerializer - unless specific constructors are used, XmlSerializer would keep on generating more dynamic assemblies and thereby increasing memory foot-print. Quote from MSDN on the same:

Dynamically Generated Assemblies

To increase performance, the XML serialization infrastructure dynamically generates assemblies to serialize and deserialize specified types. The infrastructure finds and reuses those assemblies. This behavior occurs only when using the following constructors:

XmlSerializer.XmlSerializer(Type)

XmlSerializer.XmlSerializer(Type, String)

If you use any of the other constructors, multiple versions of the same assembly are generated and never unloaded, which results in a memory leak and poor performance. The easiest solution is to use one of the previously mentioned two constructors. Otherwise, you must cache the assemblies in a Hashtable, as shown in the following example.

My advise would be to of course find out the actual reason for using undocumented code from generated assembly from concerned developers but regardless prepare to migrate away from the same by using XmlSerializer/XmlSerializerFactory - you can always use your own caching solution if needed (in case you are not using those two particular constructors). Don't forget to test your code rigorously.

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing answer. Thank you for providing such a thorough (and well documented) response! This helped me out immensely.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.