【问题标题】:Unity 2.0: How to create child containers on CTor injection?Unity 2.0:如何在 CTor 注入上创建子容器?
【发布时间】:2011-03-08 09:10:29
【问题描述】:

我有一个 MessageSender 类,它的构造函数如下所示:

    public MessageSender(IInputComponent input, IOutputComponent output)
    {
        m_Input = input;
        m_Output = output;
    }

这就是我实例化它的方式:

    Container.RegisterType<IMessageSender, MessageSender>();
    Container.RegisterType<IInputComponent, KeyboardInput>();
    Container.RegisterType<IOutputComponent, ScreenOutput>();
    Container.RegisterType<ILogger, Logger>();
    return Container.Resolve<IMessageSender>();

这是 KeyboardInput 构造函数:

    public KeyboardInput(IUnityContainer container)
    {
        m_Container = container;
        m_Logger = container.Resolve<ILogger>();
    }

我希望 KeyboardInput 实例接收一个子容器给它的构造函数,所以它会从子容器而不是父容器解析它的记录器。

我怎样才能做到这一点?

谢谢!

【问题讨论】:

    标签: dependency-injection inversion-of-control unity-container ioc-container


    【解决方案1】:

    您不应该在 KeyboardInput 或任何其他类中依赖 IUnityContainer。 DI Container 应该解决所有组件并让开 - 我称之为Hollywood Principle for DI。保持对容器的引用指向Abstract Service Locator anti-pattern,所以这是一个非常糟糕的主意。

    Krzysztof Koźmic 最近的这些帖子很好地解释了这一点:

    始终可以重新设计对象模型,从而无需引用容器。为什么你认为你需要 KeyboardInput 中的容器?

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2020-02-20
    • 1970-01-01
    相关资源
    最近更新 更多