What is dependency injection?
DI is a way to apply the Inversion of Control (IoC) principle. We could regard 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 program’s entry point (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. Instead, A
should use an interface, I
, implemented by B
, and B
should be resolved and injected at runtime.
Let’s decompose this:
- Object
A
should depend on interfaceI
instead of concretionB
. - Instance
B
, injected intoA
, should be resolved at runtime by the IoC container. A
should not be aware of the existence ofB
.A
should not control the lifetime ofB
.
To go all out LEGO®, we could...