What is dependency injection, and is it overused?
Dependency injection (DI) sounds complicated, but the core idea is simple: instead of a piece of code creating the things it depends on, those things are passed in from outside.
Without DI:
A ReportService creates its own database connection and email client inside its constructor.
With DI:
ReportService receives a database and an email client as parameters. Whoever creates it decides which implementations to pass.
Why it helps:
- Testing: pass in a fake database or email client
- Flexibility: swap implementations (for example a different storage backend) without changing the service
- Clear dependencies: you can see what a component needs from its constructor
DI containers and frameworks automate wiring: you register components and the container builds the graph. Common in Java, C# and some TypeScript frameworks.
Where it gets overused:
- Interfaces created for every class, even with one implementation forever
- Magic auto-wiring that makes it hard to find where something comes from
- Deep layers of indirection for small applications
- Configuration errors that only show up at runtime
A pragmatic middle ground: pass dependencies as constructor or function parameters by hand ("pure DI"), and only adopt a container when wiring becomes painful. In functional styles, passing functions or using closures achieves similar results.
Do you use a DI framework or wire things manually? Where has DI made code harder to follow for you?
Comments · 3
The example helped. So "passing in" the database means I can pass a fake one when testing without changing the service code?
Overused when it's a framework doing magic for a three-class app. Plain constructor arguments give you 90 percent of the benefit.
Value to the business is faster tests and easier swaps of vendors. The cost is extra complexity, so introduce it where changes are likely.