Dependency Injection
What is it?
Dependency injection is a technique where a component is given the things it needs from outside, rather than creating them itself.
Explain like I'm 5
Why was it created?
When a class builds its own dependencies, it's hard to change or test. DI was adopted to supply them externally, loosening that coupling.
Where is it used?
- Wiring up services in apps
- Making code testable
- Swapping implementations
- Framework architecture
Why should developers care?
DI is central to testable, flexible code and is built into many frameworks, so developers encounter it constantly.
How does it work?
Instead of a class instantiating its dependencies, they're passed in — through the constructor, a setter, or a framework's container. The class depends on an abstraction, so you can supply real or fake implementations.
Real-world example
A service receives a database connection as a constructor argument; in tests you pass a fake one, so no real database is needed.
Common use cases
- Unit testing with fakes/mocks
- Swapping implementations
- Decoupling components
- Centralized wiring
Advantages
- Easier testing
- Loose coupling
- Flexible to swap implementations
- Clearer dependencies
Disadvantages
- Adds indirection
- DI frameworks can feel like magic
- Over-use complicates simple code
- Harder to trace wiring
When should you use it?
When you want testable, swappable components and clear dependencies.
When should you avoid it?
For trivial code where passing dependencies adds needless ceremony.
Alternatives
Related terms
Interview questions
Beginner
- What is dependency injection?
- Why not let a class create its own dependencies?
Intermediate
- How does DI help testing?
- What is constructor injection?
Senior
- How does DI relate to the Dependency Inversion principle?
- When does a DI container help versus hurt?
Common misconceptions
- "DI requires a special framework" — passing dependencies into a constructor is dependency injection, no framework needed.
- "DI and Dependency Inversion are the same" — DI is a technique; Dependency Inversion is the broader principle it supports.
Fun facts
- The simplest form of DI is just passing arguments into a constructor.
- DI is what makes swapping a real database for a fake one in tests easy.
Timeline
- 2000s — DI popularized by frameworks and the SOLID principles
Learning resources
Quick summary
Dependency injection supplies a component's dependencies from outside, loosening coupling and making code far easier to test and swap.
Cheat sheet
- Pass dependencies in, don't create them
- Depend on abstractions
- Enables testing with fakes
- Constructor injection is the simplest form