I understand that the Dependency Injection principle is all about decoupling code. Instead of making new instances in the classes, instead you inject them, which make them loosely coupled.
Now if I have to pass on a set of objects that will be used through several classes throughout my application, I can make a container (commonly called dependency injection container).
That is exactly what i am doing because I have to pass a config object, a logger object, a translator object, etc. which will be used through several classes instances of my application. I am passing the whole container through several classes, even if not all of the classes need access to all the objects within the container. This led me to the following question: what is the difference if I create a global Registry and put the objects in there, then retrieve them like Registry::getInstance()->get('logger'); ? Wether I use a global registry or a dependency container, class isntances will have access to all the objects within the container or registry, even if they don't need to see/access all of them.
Conclusion: What is the difference if I pass a dependency injection container along my classes or a global Registry ?
I agree with most of what teresko has said and i would like to add some points:
I think the point missing here is CompositionRoot .As per DI Principle once you define your bindings in the Composition Root , then you can use the reference throughout the application. That is the value DI Container brings.
As per definition "A Composition Root is a (preferably) unique location in an application where modules are composed together."
I will add that a Composition Root also a unique location where all important decisions about your applications behavior takes place. That is what object to use in what situation.This is the heart of a OO system where interaction between the objects deliver the behavior of the system.
Use of global Registry causes your code to be tied to the class name of said Registry. It means that you cannot test your code independently. And the way, how registry is set up, lies to you: you can never know which instance will be required.
DI Container is not something that you inject into a class. Instead it is an enhancement for factories: it determines that class
Foo
requires instance ofBar
to be injected in the constructor. Then, depending on setup, it either acquires new instance ofBar
or uses the existing one, to provide said dependency.In a simple factory you usually have to hard-code the dependencies, that will be injected. In this situation, what factory can build, is limited by "footprint" of class's constructor.
When factory uses as DI container, it can produce instances with various dependencies. In this setup, your factories focus on constructing instances that are tied to some specific namespaces (or other high-level) logical groups of classes.