Search code examples
architecturedependency-injectioninversion-of-controlninjectconstructor-injection

Serialization vs ctor injection and protecting invariants


I could be missing something obvious here...

But as I learn to appreciate the glory of IoC and ctor injection I am having trouble reconciling this with object graph serialization. Are the two patterns compatible? Why (or why not)?

Suppose there is:

public class Foo
{
    #region invariants
    private readonly List<IBar> _bars;
    private readonly Guid _id;
    #endregion

    public Foo( List<IBar> bars, Guid id )
    {
        _bars = bars.CannotBeNull("bars");
        _id = id.CannotBeNull("id");
    }

    public List<IBar> Bars { get { return _bars; } }

    //some other state I want serialized
}

public static class Ex
{
    public static T CannotBeNull<T>( this T obj, string paramName = "" )
    {
        if ( null == obj ) throw new ArgumentNullException(paramName);
        return obj;
    }
}

I like the iron clad saftey of protecting class invariants through ctor injection. It gives my objects the certainty that they will always have what they need. Is injection of invariants at odds with the repository pattern? Maybe there is a DTO layer and a factory pattern somewhere that bridges the gap... ?

Looking for sagely advice... Are the two patterns compatible? Why (or why not)?

PS: I know about IDeserializationCallback but I don't see how it helps with 'private readonly' invariants


Solution

  • There is an article by Mark Seemann about that topic, At the Boundaries, Applications are Not Object-Oriented. Bottom line is: at the borders applications are not object oriented. If there is some kind of translation (like serialization) happening, your class invariants can't be protected.