Dependency Injection Without the Framework Hype
Dependency injection (DI) sounds like enterprise jargon, but the idea is simple and it shows up in object-oriented design interviews and code reviews all the time.
The idea
A class should receive the things it depends on instead of creating them itself.
Without DI, an OrderService constructs its own PostgresOrderRepository and SmtpEmailSender inside its constructor. It is now welded to a database and a mail server.
With DI, OrderService takes an OrderRepository and an EmailSender as constructor parameters. Whoever builds the service decides which implementations to pass.
Why it matters
- Testability: in unit tests you pass an in-memory repository and a fake email sender. Tests run in milliseconds with no network.
- Swappable implementations: move from SMTP to an email API by changing one line where objects are wired together.
- Explicit dependencies: the constructor signature documents what the class needs. A constructor with nine parameters is a design smell telling you the class does too much.
- Lifetime control: the composition code decides whether a dependency is a singleton, per request or per call.
Styles
- Constructor injection: the default choice; dependencies are required and immutable.
- Setter or property injection: for optional dependencies; risk of half-initialized objects.
- Parameter injection: pass the dependency to the single method that needs it, e.g. a clock for time-based logic.
Do you need a container?
Containers (Spring, .NET's built-in container, Dagger, Guice) automate wiring in large apps. For small and medium services, manual wiring in one composition root (main function) is often clearer: plain code, no reflection, and errors at compile time. In Go and many Python codebases, manual DI is the norm.
Common mistakes
- Service locator: classes call a global registry to fetch dependencies, which hides them again.
- Injecting everything, including simple value objects and pure functions.
- Interfaces with exactly one implementation created only "for DI"; inject the concrete class until a second implementation or a test double is actually needed.
Interview tip
When an interviewer asks how you would test a class that sends emails or reads the current time, answer with DI: inject an EmailSender and a Clock, then pass fakes in tests.
Disclosure: I work with the Linkjob AI team, makers of an AI interview copilot (Linkjob AI).