문제

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

도움이 되었습니까?

해결책

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.

다른 팁

I'm not clear on what your question has to do with the repository pattern. Do you need to serialize your repository?

In any case, using XML serialization comes with the limitation of having to have setters on your properties. Like you, I prefer to keep class invarients to the constructor, so I find this painful as well. It's simply a reality of using XML serialization in .Net, so you don't have a choice (I think you can write custom serializers, but it's a pain IIRC).

If you have the option, you might look at switching to binary serialization, which can serialize private member variables. Best source I can find is here.

Edit: I guess to answer your question more directly: the patterns themselves are not at odds, but the technology implementation (when using XML Serialization) makes them incompatible.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top