序列化与ctor注入和保护不变量

dFl*_*lat 2 architecture dependency-injection ninject inversion-of-control constructor-injection

我可能会遗漏一些明显的东西......

但是当我学会欣赏IoC和ctor注入的荣耀时,我很难将它与对象图序列化协调起来.这两种模式是否兼容?为什么或者为什么不)?

假设有:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我喜欢通过注射器保护不变量的铁质安全性.它让我的对象确信他们将永远拥有他们所需要的东西.注入不变量是否与存储库模式不一致?也许在某个地方有一个DTO层和一个工厂模式来填补这个空白......?

寻找sagely建议......两种模式是否兼容?为什么或者为什么不)?

PS:我知道IDeserializationCallback,但我不知道它对'private readonly'不变量有什么帮助

Seb*_*ber 5

Mark Seemann有一篇关于该主题的文章,在边界,应用程序不是面向对象的.底线是:在边界处应用程序不是面向对象的.如果发生某种翻译(如序列化),则无法保护您的类不变量.