Dependency Injection (DI) is a form of Inversion of Control where a class receives its dependencies from the outside rather than creating them itself. The dependencies are injected into the class, typically through its constructor.
NOTE
It’s like ordering coffee at a cafe instead of making it yourself. You specify what you need, and the barista prepares it for you.
Why Use DI?
- Decoupling — Classes don’t know how to create their dependencies, just how to use them
- Testability — Inject mocks or stubs during testing
- Flexibility — Swap implementations without changing the dependent class
How to Implement
There are two key pieces:
- Constructor Injection — The technique for receiving dependencies
- Composition Root — The place where dependencies are wired together
Approaches
- Manual DI — You explicitly wire dependencies in a Composition Root
- DI Container — A framework (Spring, dependency-injector) manages creation and injection automatically
TIP
Manual DI is a good starting point. It’s explicit, has no magic, and scales well for small to medium projects.