The OnDeserializingAttribute

Published Tue, Apr 6 2010 12:47

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

Filed under:

Comments

# LA.NET [EN] said on Wednesday, April 07, 2010 3:44 AM

Oh well…remember my last post …the happiness of getting everything working out…Well, unfortunately, things

# ASPInsiders said on Wednesday, April 07, 2010 4:24 AM

Oh well…remember my last post …the happiness of getting everything working out…Well, unfortunately, things

# LA.NET [EN] said on Monday, July 12, 2010 4:14 AM

When we create a new type and define a constructor, I guess there’s nothing wrong with expecting to see

# ASPInsiders said on Monday, July 12, 2010 4:55 AM

When we create a new type and define a constructor, I guess there’s nothing wrong with expecting to see

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover