Dependency Injection
Supplying an object's dependencies from outside — constructor, setter and interface injection, the composition root, DI containers (Spring, Guice, FastAPI, NestJS), scopes, and testing with fakes.
Dependency injection (DI) means an object receives the objects it depends on instead of creating or looking them up itself. It's the most practical way to apply the dependency inversion principle, and it's what makes code testable.
class OrderService {
private final OrderRepository repo =
new PostgresOrderRepository(
"jdbc:postgresql://prod/db");
private final EmailSender mail =
new SmtpEmailSender("smtp.prod");
}- Hard-wired to Postgres and SMTP
- Tests hit a real database and send real email
- Configuration buried inside the class
class OrderService {
private final OrderRepository repo;
private final EmailSender mail;
OrderService(OrderRepository repo,
EmailSender mail) {
this.repo = repo;
this.mail = mail;
}
}- Depends only on interfaces
- Tests pass in-memory fakes
- Wiring happens in one place
Three forms
| Form | How | Use |
|---|---|---|
| Constructor injection | Dependencies are constructor parameters | Default choice: dependencies are explicit, required, and can be final/immutable |
| Setter / property injection | Set after construction | Optional dependencies; circular cases (a smell) |
| Method injection | Passed to the method that needs it | Varies per call (a request context, a clock) |
Field injection (@Autowired private Repo repo;) is convenient but hides dependencies and prevents immutability; prefer constructors.
The composition root
Somewhere, someone must create the real objects. Do it in one place at application start-up — the composition root (main, the app factory) — and nowhere else.
// Manual DI: perfectly fine for small and medium apps
public class Main {
public static void main(String[] args) {
Config cfg = Config.fromEnv();
DataSource ds = Hikari.create(cfg.dbUrl());
OrderRepository repo = new JdbcOrderRepository(ds);
EmailSender mail = new SmtpEmailSender(cfg.smtpHost());
Clock clock = Clock.systemUTC();
OrderService orders = new OrderService(repo, mail, clock);
new HttpServer(new OrderController(orders)).start(cfg.port());
}
}# Manual wiring in an app factory
def create_app(config: Config) -> App:
engine = create_engine(config.db_url)
repo = SqlOrderRepository(engine)
mail = SmtpEmailSender(config.smtp_host)
orders = OrderService(repo=repo, mail=mail, clock=SystemClock())
app = App()
app.include_router(order_routes(orders))
return app// Composition root in main.ts
const config = loadConfig();
const pool = new Pool({ connectionString: config.dbUrl });
const repo = new PgOrderRepository(pool);
const mail = new SmtpEmailSender(config.smtpHost);
const orders = new OrderService(repo, mail, systemClock);
startServer(createRouter({ orders }), config.port);DI containers
In large applications, manual wiring of hundreds of objects gets tedious. A DI container (IoC container) builds the object graph for you: you declare components and their dependencies; it figures out the construction order, creates them, and manages their lifetimes.
// Spring: classes are discovered and wired by type
@Repository
class JdbcOrderRepository implements OrderRepository { JdbcOrderRepository(DataSource ds) {...} }
@Service
class OrderService {
private final OrderRepository repo;
private final EmailSender mail;
OrderService(OrderRepository repo, EmailSender mail) { // constructor injection, no annotation needed
this.repo = repo; this.mail = mail;
}
}
@Configuration
class InfraConfig {
@Bean Clock clock() { return Clock.systemUTC(); } // explicit factory for third-party types
}# FastAPI's Depends: per-request dependency resolution
from fastapi import Depends, FastAPI
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db # cleanup after the request
finally:
db.close()
def get_order_service(db = Depends(get_db)) -> OrderService:
return OrderService(SqlOrderRepository(db), mail_sender)
@app.post("/orders")
def create_order(body: OrderIn, svc: OrderService = Depends(get_order_service)):
return svc.place(body)
# Tests: app.dependency_overrides[get_order_service] = lambda: OrderService(FakeRepo(), FakeMail())// NestJS: decorators + TypeScript metadata
@Injectable()
export class OrderService {
constructor(private readonly repo: OrderRepository, private readonly mail: EmailSender) {}
}
@Module({
providers: [
OrderService,
{ provide: OrderRepository, useClass: PgOrderRepository },
{ provide: EmailSender, useClass: SmtpEmailSender },
],
controllers: [OrderController],
})
export class OrdersModule {}Scopes (lifetimes)
| Scope | One instance per… | Typical use |
|---|---|---|
| Singleton | Application | Stateless services, connection pools, clients |
| Request / scoped | HTTP request | Database session/unit of work, current user |
| Transient / prototype | Injection | Lightweight, stateful helpers |
Testing is the payoff
@Test
void placingAnOrderSendsConfirmation() {
var repo = new InMemoryOrderRepository();
var mail = new RecordingEmailSender();
var clock = Clock.fixed(Instant.parse("2025-01-01T00:00:00Z"), ZoneOffset.UTC);
var service = new OrderService(repo, mail, clock);
service.place(new Order("o1", "alice@example.com"));
assertThat(repo.find("o1")).isPresent();
assertThat(mail.sent()).containsExactly("alice@example.com");
}def test_placing_order_sends_confirmation():
repo, mail = InMemoryOrderRepository(), RecordingEmailSender()
service = OrderService(repo=repo, mail=mail, clock=FixedClock("2025-01-01"))
service.place(Order("o1", "alice@example.com"))
assert repo.find("o1") is not None
assert mail.sent == ["alice@example.com"]test("placing an order sends confirmation", async () => {
const repo = new InMemoryOrderRepository();
const mail = { sent: [] as string[], async send(to: string) { this.sent.push(to); } };
const service = new OrderService(repo, mail, fixedClock("2025-01-01"));
await service.place({ id: "o1", email: "alice@example.com" });
expect(await repo.find("o1")).toBeDefined();
expect(mail.sent).toEqual(["alice@example.com"]);
});Notice the clock: time, randomness and environment variables are dependencies too. Injecting them makes tests deterministic.
Service locator: the anti-pattern cousin
A service locator is a global registry objects query: Registry.get(EmailSender.class). It decouples from concrete classes, but hides dependencies (you must read the code to know what a class needs) and makes tests depend on global setup. Prefer injection.
- DI: objects receive dependencies instead of creating them.
- Prefer constructor injection: explicit, required, immutable.
- Wire everything in one composition root; manual DI is fine for small apps.
- Containers (Spring, Guice, FastAPI Depends, NestJS) automate wiring and manage scopes.
- Avoid captive dependencies and service locators; inject clocks and randomness for deterministic tests.
QWhat is inversion of control?easy
A design where a framework or container, rather than your code, controls the flow or the creation of objects. Dependency injection is one form: instead of a class constructing its collaborators, the container (or composition root) constructs and supplies them. Template methods and callbacks are other forms ("don't call us, we'll call you").