Search code examples
javac#dependency-injectiondi-containers

DI-container vs. Factories


I know there are many articles and threads on Dependency Injection, but not as much on Dependency Injection Containers. I found this one by Fabien Potencier quite helpful, although it targets PHP. However the more I read about those containers I come to the conclusion that such is none more then a simple collection of factory-methods, is this true?

A deeper and more concrete view:
When injecting a dependency to an object

foo.Bar = new Dependency();

I could also write

foo.Bar = new myFactory.CreateDependency();

or with a container

foo.Bar = myContainer.CreateDependency();

Here the container within the last approach does not have only one but many other methods to create other types also, so it is just a container for factory-methods, right?


Solution

  • The whole point of DI containers is that you never need/should write code like

    foo.Bar = myContainer.CreateDependency();
    

    It is considered an antipattern. DI container should be used only once in Composition Root(it is a main DI container usage pattern).

    DI container automatically construct objects and inject dependencies via constructors or properties based on configuration. In case of Factory you have to do everything yourself. Beside creation DI containers provide you with:

    LifeTime management. So every time dependency is needed container might inject the same object(singleton lifetime), or return new everytime.

    Limited AOP capabilities such as method call interception and executing custom logic before and after methods.

    You might take a look into this book Dependency Injection in .NET. It helped me a lot to understand DI containers, patterns of usage and Dependency injection in general.