Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection Container - Factory Pattern

I have been trying to learn about dependency injection and have been reading about and trying to code a small dependency injection container similar to this: http://fabien.potencier.org/article/12/do-you-need-a-dependency-injection-container

The one thing that is confusing me is this:

Isnt a dependency injection container just a glorified implementation of the factory pattern?

If so, why not just call it that, why the need for a fancy term only to confuse matters.

If it isnt, can someone explain what i am missing here?

like image 494
Marty Wallace Avatar asked Aug 24 '12 07:08

Marty Wallace


1 Answers

You have to separate Dependency Injection and Inversion Of Control.

Dependency Injection is that you inject the dependencies into the class rather than letting the class itself be responsible of its dependencies.

Inversion Of Control is rather that something takes control over the object and it's lifetime. In this case it's up to the container to decide when and how an object should be created and disposed.

Factory pattern are all about creating a new object at each call. The pattern itself doesn't say anything about how dependencies should be created.

That's why you can configure different lifetimes and use child containers to control objects with limited lifetime.

I've written an article about that here: http://www.codeproject.com/Articles/386164/Get-injected-into-the-world-of-inverted-dependenci

Or if you like to see with more examples: http://www.codeproject.com/Articles/440665/Having-fun-with-Griffin-Container

like image 186
jgauffin Avatar answered Sep 19 '22 17:09

jgauffin