views:

38

answers:

1

Hello,

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!

+3  A: 

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?

Mark Seemann
Thanks for the response!The main reason I'd like to have the IOC container as an instance variable, is that I'd like to instantiate service proxies, that are disposable, as local variables in methods, so that I can call the Dispose() method as soon as possible.
Dor Rotman
This answer might help with that: http://stackoverflow.com/questions/3010820/dependency-injection-wcf/3011473#3011473
Mark Seemann