开发者

Unity 2.0: How to create child containers on CTor injection?

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 KeyboardI开发者_开发问答nput(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!


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:

  • How I use Inversion of Control containers
  • How I use Inversion of Control containers – pulling from the container

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜