What is Dependency Injection?
Dependency Injection (DI) is a way to apply the Inversion of Control (IoC) principle. We could see IoC as a broader version of the Dependency Inversion principle (the D in SOLID).
The idea behind DI is to move the creation of dependencies from the objects themselves to the entry point of the program (the composition root). That way, we can delegate the management of dependencies to an IoC container (also known as a DI container), which does the heavy lifting.
For example, object A should not know about object B that it is using. A should instead use an interface I implemented by B, and B should be resolved and injected at runtime.
Let's decompose this:
- Object
Ashould depend on interfaceIinstead of concretionB. - Instance
B, injected intoA, should be resolved at runtime by the IoC container. Ashould not be aware of the existence ofB.Ashould not control the lifetime ofB.
To go all out LEGO®, we could...