我可能在这里遗漏了一些明显的东西......
但是当我学会欣赏 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;
}
}
我喜欢通过 ctor 注入保护类不变量的铁皮安全。它让我的对象确信他们将永远拥有他们需要的东西。注入不变量是否与存储库模式不一致?也许在某个地方有一个 DTO 层和一个工厂模式可以弥合差距......?
寻找明智的建议...这两种模式兼容吗?为什么或者为什么不)?
PS:我知道 IDeserializationCallback 但我看不出它对“私有只读”不变量有何帮助