Dependency Injection

Give a function or class the things it needs from outside, instead of letting it create them, so they're easy to swap or test.

What is it?

Imagine a function that sends a welcome email and creates its own connection to a real email service. That's fine until you test it: every test run sends a real email over a real network and needs the third-party service up and configured. You can't swap in a fake, because the choice of service is buried inside the function.

Dependency injection flips this. Instead of creating its dependencies, a function or class receives them from outside, usually as parameters, so the caller controls what's used. A test passes a fake, predictable email service; production passes the real one.

Explain like I'm 10

A kitchen that grows its own vegetables, raises its own chickens and mines its own salt is nearly impossible to inspect or adjust. A kitchen that gets ingredients from suppliers can swap one supplier for another, including, for a health inspection, ingredients prepared specially for testing.

Examples

Without dependency injection — hard to test

const realEmailService = require("./realEmailService");

async function sendWelcomeEmail(user) {
  // The function decides, internally, exactly which service to use
  await realEmailService.send(user.email, "Welcome!");
}

This function can only use the real email service. You can't substitute anything without editing this file.

With dependency injection — swappable and testable

async function sendWelcomeEmail(user, emailService) {
  await emailService.send(user.email, "Welcome!");
}

// Production
await sendWelcomeEmail(user, realEmailService);

// Test
const fakeEmailService = { send: jest.fn() };
await sendWelcomeEmail(user, fakeEmailService);
expect(fakeEmailService.send).toHaveBeenCalledWith(user.email, "Welcome!");

The function no longer chooses the email service; it uses whatever is passed in. A test can supply a fake it can observe, without touching anything real.

How it works

A function or class that needs something (a database connection, email service, clock or logger) declares it as a parameter, or a constructor argument in object-oriented code, instead of creating or importing it inside its body.

Whoever calls it (production code, a test, or wiring set up at app startup) decides which implementation to pass. Large apps may use a dependency injection container to automate that wiring, but the idea is the same at any scale: the dependency comes from outside.

Why does it exist?

Code that builds its own dependencies is rigid: it can only run and be tested against the real ones, which is often slow, flaky or impossible in tests (you don't want tests charging real credit cards). Dependency injection separates what code needs from which implementation provides it, so code is much easier to test in isolation and to reconfigure without editing its internals.

When to use it

Use it for anything that talks to the outside world (databases, external APIs, the filesystem, the current time), especially in code you want to unit test without those real dependencies.

When not to use it

Small, self-contained functions with no external dependencies (like a pure function that formats a date) have nothing to inject. Adding indirection there is just noise.

Common mistakes

  • Importing a real dependency directly inside a function, then finding it impossible to test in isolation.

  • Over-engineering injection for simple, pure logic with no external dependencies to swap.

  • Injecting a dependency but still using a global or imported copy elsewhere in the same code path, defeating the purpose.

Practice exercises

  1. Easy:

    Rewrite a function that calls Date.now() internally so the current time is passed in as a parameter instead.

  2. Medium:

    Refactor a function that imports and uses a real database client so it accepts the client as a parameter instead.

  3. Hard:

    Write a test for chargeCustomer(order, paymentService) using a fake paymentService, and explain what real-world problems that avoids compared with testing against the real payment provider.

Interview questions

What is dependency injection?

A design approach where a function or class receives what it depends on from outside (usually as parameters or constructor arguments) instead of creating or importing it internally.

Why does dependency injection make code easier to test?

A test can pass a fake, predictable version of a dependency (like a fake email service or database) instead of the real one, avoiding slow, flaky or unsafe real side effects.

Give an example of a dependency worth injecting rather than hardcoding.

An external service client (email, payments, a database connection), or even the current time: anything a test would want to replace with a controlled fake.

What's the difference between constructor injection and parameter injection?

Constructor injection passes dependencies when an object is created and stores them on the instance (e.g. this.db) for every method. Parameter injection passes a dependency into one function call only.

Why might constructor injection suit a class better than parameter injection, if many of its methods all need the same database connection?

It avoids threading the same parameter through every method's signature. The dependency is supplied once at construction, and every method uses this.db.

What is inversion of control, and how does dependency injection relate to it?

Inversion of control is the principle that a component shouldn't decide how its dependencies are built or found. Dependency injection is one way to achieve it: the choice of which implementation to use moves outward, to whoever wires the component up.

What problem does a dependency injection container solve as an application grows?

It builds and wires a whole graph of dependencies from registered rules, so you don't thread every dependency through every layer by hand.

How does NestJS build dependency injection into the framework itself?

A NestJS class lists what it needs as constructor parameters, and NestJS's container builds and supplies matching instances at runtime. You rarely construct a dependency by hand.

In FastAPI, how does `Depends()` implement dependency injection for a route handler?

A route parameter's default is set to Depends(some_function). FastAPI calls some_function and injects its return value as the argument, so the handler never builds that dependency itself.

What's the difference between a stub, a mock, and a fake, as types of test doubles?

A stub returns preset values and doesn't check how it was called. A mock records calls so a test can assert specific interactions. A fake is a simplified but working implementation, like an in-memory database in place of a real one.

In the sendWelcomeEmail example, why is `jest.fn()` specifically useful as the fake `emailService.send`?

jest.fn() creates a mock function that records every call, so the test can assert exactly which arguments were passed. A plain stub that just returns a value can't check that.

What is the service locator pattern, and why is it often considered worse than dependency injection?

A class asks a central registry for its dependencies by name or type at runtime, instead of receiving them as parameters. That hides the class's real dependencies in its body and makes testing harder, since a test must configure the shared locator instead of just passing a fake.

Why does dependency injection often go hand-in-hand with depending on an interface rather than a concrete class?

The consumer only needs the shape it depends on (e.g. 'something with a .send() method'), not which class provides it. That's what lets you swap a real service for a fake without touching the consumer's code.

Debugging: a test injects a fake database, but the function under test still hits the real one. What's a likely cause?

The function probably still imports and uses the real database client somewhere in its body, besides the injected parameter. Injecting one copy while using a global or imported one elsewhere defeats the point.

Given `async function sendWelcomeEmail(user, emailService) { await emailService.send(...) }`, what happens if it's called as `sendWelcomeEmail(user)` with no second argument?

emailService is undefined, so calling .send(...) throws a TypeError at runtime. Dependency injection makes the caller responsible for passing a valid dependency; this is what happens when it forgets.

Trap: a developer adds dependency injection to a pure function like `add(a, b)`. What's wrong with that?

There's nothing to swap or fake. A pure function with no external dependencies gains no testability from injection, only an extra parameter and indirection.

What is a singleton dependency lifetime in a DI container, and when is it appropriate?

The container builds the dependency once and gives the same shared instance to every consumer. Use it for something stateless or expensive to build, like a database connection pool, where creating a new one per use would be wasteful or wrong.

How does a transient lifetime differ from a singleton one?

A transient dependency is built new every time it's requested, not shared. Use it when instances must not carry state between uses, at the cost of paying construction overhead each time.

Why is dependency injection considered especially important for code that talks to the outside world, like databases or the filesystem?

Those dependencies are slow, non-deterministic, stateful, or unsafe to use for real in automated tests. Swapping in a controlled fake is what makes that code testable at all.

Scenario: you need to test a function that checks 'is this coupon still valid?' based on the current time. How does injecting the clock help?

The test passes a fixed, known timestamp instead of the real current time, so it's deterministic and repeatable whenever it runs, including at a boundary like midnight that a real clock can't reliably reproduce.

What's a real cost of taking 'program to an interface' too far when applying dependency injection?

Adding an interface and injection point for a dependency that will only ever have one implementation adds boilerplate and indirection with no real testability or flexibility gain.

How does dependency injection support the single responsibility principle?

A class that builds its own dependencies does two jobs: its own logic, and deciding how to build or configure a collaborator. Injection removes the second job, so the class focuses on its logic.

Why inject a logger instance instead of importing a global logger directly?

A test can inject a no-op or in-memory logger to keep output clean and assert on what was logged. Different environments (production, a CLI tool, a test run) can get different logging without changing the function's code.

How is dependency injection different from just passing plain configuration values, like a port number, as parameters?

Dependency injection means supplying behavior: an object with methods the code calls, like a service or client. Passing plain data, like a config value, isn't usually what 'dependency injection' means on its own.

Follow-up: once a database dependency is injected into a function, how do you avoid every caller having to explicitly pass it at every call site?

Wire the real dependency once at the app's composition root at startup, or let a DI container manage it, so it flows through from one place instead of being passed by hand at every layer.

What real-world problem does injecting a fake payment service avoid, compared to testing against a real payment provider?

It avoids charging a real card, needing network access to a third party, and slow or flaky test runs caused by that service's availability or rate limits.

How does a module-mocking tool like `jest.mock()` achieve a similar benefit to dependency injection without changing a function's signature?

It intercepts module resolution and swaps a module's real implementation for a mock wherever it's imported. You get a similar testing benefit by replacing the import, without the function taking the dependency as a parameter.

Trap: a test's fake service has a different method signature than the real service it replaces. What risk does this create?

The test can keep passing while the fake quietly drifts from the real dependency's contract, giving false confidence. Keep fakes honest against the real interface, for example by having both implement a shared, typed interface.

Why is dependency injection often described as a form of loose coupling?

The consumer depends only on an abstract need ('something that can send an email'), not the specific module that provides it. The two are connected only by what's passed in at the call site, so either can change independently.