WCF Serialization Part 2b: WCF Collection Serialization

As we mentioned here, I'm currently struggling with getting WCF to serialize my NameValueCollection object on a service operation. The previous post goes over the general details, while here I'll dive a bit deeper. It's recommended to read the first part before continuing.


I don't know exactly the logic that goes in the WCF serialization engine to determine what data contract will be selected for serialization.. I tried wading in with Reflector but got a bit lost. I managed to track down some interesting places, though. Both in the System.Runtime.Serialization assembly:


  • System.Runtime.Serialization.DataContract.CreateDataContract() 

This is apparently called when the serializer needs to decide what datacontract applies to the object, if nothing more explicit is found. We can see in line 38 that the function tries to create an instance of the collection type, which leads us to:


  • System.Runtime.Serialization.CollectionDataContract.IsCollectionOrTryCreate() 

This method checks if the type is a collection in various ways (interfaces implemented, etc), and has an explicit check if the type has an Add method that receives an object parameter (line 110):

itemType = type3.IsGenericType ? type3.GetGenericArguments()[0] : Globals.TypeOfObject;
CollectionDataContract.GetCollectionMethods(type, type3, new Type[] { itemType }, false, out info2, out info1);
if (info1 == null)
   // Handle invalid collection


I'm not entirely clear on the entire logic flow, but these two places seem to indicate that the WCF engine sees the NVC, flags it as a Collection (maybe due to it implementing ICollection) then makes sure it stands up to its strict requirements (stricter than just implementing ICollection) and throws an exception when it doesn't.


The big question here is why the IsCollectionOrTryCreate() method, which should return bool if the type is not a collection, instead chooses to throw an exception when it's an incompatible collection rather than returning false and letting the ISerializable handler take it from there.


In my next post: Some ugly hacks that also didn't work.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.