intermediate

Dependency Injection

Provide collaborators from the outside so policy code stays testable and does not hard-code infrastructure choices.

Dependency injection supplies collaborators from the outside—constructors, factories, or containers—so policy code does not hard-code infrastructure. It enables swapping databases, clocks, and HTTP clients in tests and environments. Prefer constructor injection for required dependencies and explicit lifetimes.

On interviews: contrast DI with service locator and global singletons. Explain scoped versus singleton lifetimes in web requests.

Common pitfalls: container resolve calls scattered in domain code; circular provider dependencies; injecting ten optional dependencies instead of redesigning boundaries.

The trade-off is flexibility versus complexity—know when the simpler path is enough.

Checklist:

  • Depend on interfaces at policy boundaries.
  • Wire composition root in application startup.
  • Document lifetime per service registration.
  • Tests construct objects with manual doubles.