This is the last part of my continuing saga of serializing dictionaries over WCF and beyond.
Quick recap: While WCF allows me to serialize an IDictionary easily, trying to serialize that dictionary later for other uses fails – specifically, caching it to disk using the Enterprise Library. This is because the Enterprise Library relies on the BinaryFormatter, which in turns relies on the type implementing ISerializable. An alternate solution was to use the NameValueCollection which implements ISerializable, but is incompatible with WCF's serialization.
I felt trapped, having to juggle between two incompatible serialization engines – one for communications, one for persistance. Frustrated. Annoyed. Helpless.
But then, as I was whining to my teammates, the solution came to me – there really isn't any reason to jump from one serialization method to the other. Since WCF gives me the most freedom and lets me use the IDictionary that I want, I can simply use WCF's serializer – the NetDataContractSerializer – for the Enterprise Library's cache serialization.
Going over EntLib's code proved very easy – the Caching project has a class called SerializationUtility that exposes two methods – ToBytes() and ToObject(). I'll reproduce the entire method, just to illustrate how simple it is:
Given this simple method (and its even simpler brother, ToObject()) it's not hard to see that all the work that needs to be done is adding a reference to System.Runtime.Serialization and replacing BinaryFormatter with NetDataContractSerializer – and that's it. Their methods have identical signatures, so there's no work there, either.
The lovely thing about EntLib is that it comes with comprehensive unit tests. The only thing I did after making this change is letting NUnit chew on the 200-odd test methods defined and give me a positive result, and I'm good to go.
I've attached the new SerializationUtility.cs for those too lazy to make the change themselves, and the compiled Microsoft.Practices.EnterpriseLibrary.Caching.dll for those who want to just drop it in. Enjoy.