architecture - 序列化与 ctor 注入(inject)和保护不变量

标签 architecture dependency-injection inversion-of-control ninject constructor-injection

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

但是当我学会欣赏 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/

相关文章:

sql - 我将如何为读写操作实现单独的数据库?

python - Apache Airflow 或 Luigi 是适合此用例的好工具吗?

architecture - 设计文档(高级和低级设计文档)

asp.net-mvc-3 - Ninject MVC 3 - 将依赖项注入(inject)模型和 Controller

ruby-on-rails - 将单个复杂应用程序拆分为单独的应用程序是否有利于代码库的可维护性?

javascript - Angular UI Router - 子状态的解析始终等待父状态解析

php - Laravel 5 - 方法注入(inject)

c# - 使用 Ninject(或其他一些容器)我如何找出请求服务的类型?

c# - 新 MVC3 项目中的 InversionOfControl

c# - 依赖注入(inject)在 C++ 中有用吗