LA.NET [EN]

Apr 06

The OnDeserializingAttribute

Posted in WCF      Comments Off on The OnDeserializingAttribute

Since I’m porting an existing project to .NET 4.0, I’ve thought about using code contracts in order to improve my code base (and yes, I can say that after some initial frustrations, code contracts is my pal now :),,). And yes, it did improve…but since I’m using runtime exceptions, that also meant that I started getting unexpected runtime exceptions.

One of my DTOs had an invariant which specified that a specific object can never be null. To ensure that, I’ve introduced my own default constructor which was responsible for initializing that field into a valid (default) value. And everything run fine until I tried to recover an instance of that object through a WCF service. It was only then that I’ve recalled about an old problem that had bit me in the past: the constructor of a type isn’t called during deserialization!

Fortunately, there’s a solution for this problem: the OnDeserializingAttribute. That means that I’ll have to refactor the initialization code into a helper method so that it gets called during “normal” instantiation and during deserialization. A little more work, but at least I can still keep my invariants valid. Hurray!

Now, if I could only get NHibernate to play nicely with .NET HashSet