我可能会在这里遗漏一些明显的东西......
但是当我学会欣赏 IoC 和 ctor 注入(inject)的荣耀时,我很难将其与对象图序列化协调起来。这两种模式兼容吗?为什么(或者为什么不)?
假设有:
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;
}
}
我喜欢通过 ctor 注入(inject)来保护类不变量的铁定安全。它让我的对象确信他们将永远拥有他们需要的东西。不变量的注入(inject)与存储库模式不一致吗?也许有一个 DTO 层和一个工厂模式可以弥补这个差距......?
寻求明智的建议...这两种模式兼容吗?为什么(或者为什么不)?
PS:我了解 IDeserializationCallback,但我不知道它对“私有(private)只读”不变量有什么帮助
最佳答案
Mark Seemann 有一篇关于该主题的文章,At the Boundaries, Applications are Not Object-Oriented 。底线是:在边界应用程序不是面向对象的。如果发生某种类型的转换(例如序列化),则您的类不变量将无法受到保护。
关于architecture - 序列化与 ctor 注入(inject)和保护不变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8958251/