Unity 2.0:如何在 CTor 注入上创建子容器?

发布于 2024-09-07 10:02:47 字数 862 浏览 3 评论 0原文

我有一个 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 实例将子容器接收到其构造函数,因此它将从子容器解析其记录器,并且不是父母。

我怎样才能做到这一点?

谢谢!

I have a MessageSender class that its constructor looks like this:

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

This is how I instantiate it:

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

Here is the KeyboardInput consutructor:

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

I want the KeyboardInput instance to receive a child container to its constructor, so it will resolve its logger from the child container and not the parent.

How can I accomplish that?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末骤雨初歇 2024-09-14 10:02:47

您不应该依赖 KeyboardInput 或任何其他类中的 IUnityContainer。 DI 容器应该解析所有组件并避开 - 我称之为 DI 的好莱坞原则。保留对容器的引用会导致抽象服务定位器反模式,所以这是一个非常糟糕的主意。

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

总是可以重新设计对象模型,以便不需要引用容器。为什么你认为你需要 KeyboardInput 中的容器?

You are not supposed to take a dependency on IUnityContainer in KeyboardInput or any other class. A DI Container should resolve all components and get out of the way - I call this the Hollywood Principle for DI. Keeping a reference to the container leads towards the Abstract Service Locator anti-pattern, so that's a spectacularly bad idea.

These recent posts by Krzysztof Koźmic explains it pretty well:

It's always possible to redesign the object model so that referencing the container isn't necessary. Why do you think you need the container in KeyboardInput?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文