问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/12105155/dependency-injection-container-factory-pattern