The OnDeserializingAttribute – part II
Oh well…remember my last post…the happiness of getting everything working out…Well, unfortunately, things stopped working (read: code contract started generating exceptions) when you define more than one invariant. Here’s my initial code:
public class Dumb
{
public String A { get; set; }
public String B { get; set; }
public Dumb()
{
Initialize();
}
[OnDeserializing]
private void DeserializerHelper()
{
Initialize();
}
private void Initialize()
{
A = B = "";
}
[ContractInvariantMethod]
private void Invariants()
{
Contract.Invariant( A != null);
Contract.Invariant( B != null);
}
}
When you use code contracts and configure it so that it’s also used at runtime, you’ll start getting exceptions when an instance of Dumb is deserialized. The problem here is that setting B to “” will end up checking the object’s invariants and that means that A is still null (and there you go: an exception). The only workaround for this is using backing fields for each property and changing the initialization code so that it uses those new backing fields (instead of going through the properties). I guess you could always dismiss code contracts on objects that are used by WCF services, but that seems worst than using backing fields…