Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency injection: How to pass the injection container around?

(This question does not rely on a specific IoC framework, so the interfaces and types in my samples are meta-types. Just replace them with the appropriate types for your favorite IoC framework in your head.)

In my main methods, I typically set up my container doing something like this:

static void Main()
{
    IInjector in = new Injector();
    in.Register<ISomeType>().For<SomeType>();
    in.Register<IOtherType().For<OtherType>();
    ...

    // Run actual application
    App app = in.Resolve<App>();
    app.Run();
}

My question is, how do you get the Injector sent around? I've normally just registered the injector with itself and had it injected into types that themselves are going to do injection, but I'm not sure if this is the proper "pattern".

like image 713
Alex Avatar asked Mar 29 '10 17:03

Alex


1 Answers

You shouldn't pass the container around.

Instead, your entry-point/main method asks the container for the objects it needs to get started - such as your App object/bean. The container then returns the full object graph connected to App, which allows you to run app.Run(), with all the dependencies satisfied.

It's a bit of an anti-pattern for the objects to be aware of the container, or for each object to be asking the container for it's dependencies - if you do this then you have not inverted control and what you have is not dependency injection - you still have objects asking for what they need, rather than being given what they need.

like image 179
matt b Avatar answered Sep 17 '22 13:09

matt b