You sit down to write a unit test for placeOrder. Thirty seconds later the test is still hanging, because somewhere inside the method a real Postgres client is trying to connect and a real payment SDK wants an API key. You never asked for either. The method went and got them on its own.
That's the whole problem dependency injection solves. A class that builds its own collaborators is hard to test, hard to change and hard to read. The fix sounds almost too small to have a name: let someone else build the collaborators and hand them in. Containers, decorators and injection tokens all sit on top of that one move, and once you've seen the plain version, the frameworks stop looking like magic.
This post walks through it in order: the hard-wired version, where the names IoC and DI come from, constructor injection, the composition root, when a container is worth it, and the mistakes that undo the benefits. The examples are TypeScript, but the ideas carry over to Java, C#, Kotlin or Go as they are.
The hard-wired version: a class that calls new on its own
Here's an order service that looks fine at first glance:
// order-service.ts (before): the service builds its own tools
class OrderService {
async placeOrder(cart: Cart): Promise<Order> {
const db = new PostgresClient(process.env.DATABASE_URL!)
const payments = new StripeClient(process.env.STRIPE_SECRET_KEY!)
const mailer = new SendGridMailer(process.env.SENDGRID_API_KEY!)
const order = Order.fromCart(cart)
await payments.charge(order.total, cart.paymentToken)
await db.query('INSERT INTO orders (id, total) VALUES ($1, $2)', [order.id, order.total])
await mailer.send(cart.email, 'order-confirmed')
return order
}
}
Try to work with it and three problems show up fast:
- You can't test it alone. Running
placeOrderneeds real credentials, a live database and a payment sandbox. Every test becomes a slow integration test, whether you wanted one or not. - It's welded to specific vendors. Moving from Stripe to Adyen means editing business logic. Using a fake mailer on staging means adding an
iffor the environment. - Its needs are invisible. The signature says
placeOrder(cart). Nothing tells a reader that the method also needs a database, a payment provider and an email service until they read every line.
A new SomeExternalThing() inside a method or constructor body, anywhere outside your app's entry point. That class now has two jobs: doing its work, and finding and building the tools for that work. The second job is the one that makes it hard to test and change.
Inversion of Control: who's in charge of creating things?
Inversion of Control is older than DI and wider. Martin Fowler traces the term back to Ralph Johnson and Brian Foote's 1988 paper "Designing Reusable Classes", the earliest use he could find, and describes it as the line between a library and a framework: you call a library, but a framework calls you (Fowler, InversionOfControl). That's the "Hollywood Principle" you may have heard: don't call us, we'll call you.
So IoC is the general idea that control over some decision moves out of your code and into something around it. That something can be a framework, a test, or the startup code of your app. You'll find it in several shapes:
- Dependency Injection: collaborators arrive as constructor or method parameters. The most explicit form, and the one this post is about.
- Service Locator: code asks a registry for what it needs by name. It also moves creation out of the class, with trade-offs we'll get to.
- Template Method: a base class runs the flow and calls hooks that subclasses fill in.
- Events and callbacks: you register a handler, and the framework decides when to call it.
In 2004, when lightweight Java containers like Spring and PicoContainer were taking off, Fowler wrote that "Inversion of Control is too generic a term, and thus people find it confusing" and settled on the name Dependency Injection for the specific pattern those containers used (Fowler, Inversion of Control Containers and the Dependency Injection pattern). So the short version: IoC is the principle, DI is one concrete way to apply it to object creation.
Dependency Injection: hand the collaborators in
The mechanics are almost embarrassingly small. Stop constructing collaborators inside the class. Declare them as parameters and let the caller provide them. Fowler's article names three forms: constructor injection, setter injection and interface injection. The last one barely shows up in modern code, so we'll stick to the first two.
Constructor injection (your default)
Everything the class always needs goes in the constructor. Each dependency is visible in the signature, required up front, and can be readonly so nothing swaps it out later.
// order-service.ts (after): dependencies come in through the constructor
interface PaymentGateway { charge(amount: Money, token: string): Promise<Receipt> }
interface OrderRepository { save(order: Order): Promise<void> }
interface Mailer { send(to: string, template: string): Promise<void> }
class OrderService {
constructor(
private readonly payments: PaymentGateway,
private readonly orders: OrderRepository,
private readonly mailer: Mailer,
) {}
async placeOrder(cart: Cart): Promise<Order> {
const order = Order.fromCart(cart)
await this.payments.charge(order.total, cart.paymentToken)
await this.orders.save(order)
await this.mailer.send(cart.email, 'order-confirmed')
return order
}
}
Read the constructor out loud: to make an OrderService, you need a payment gateway, an order repository and a mailer. That's the contract, and you can see it without opening a single method. The Spring docs give the same advice and the same reason: the Spring team "generally advocates constructor injection" because it gives you immutable objects, required dependencies that can't be null, and components that are fully initialized when you get them (Spring Framework reference).
Setter injection (for the occasional optional piece)
Here the dependency gets set after construction. It fits a collaborator that really is optional and has a sensible default. The cost is that the object can exist half-configured for a while, and bugs like to live in that gap.
// setter injection: only for a collaborator that is truly optional
class ReportGenerator {
private formatter: ReportFormatter = new PlainTextFormatter()
setFormatter(formatter: ReportFormatter): void {
this.formatter = formatter
}
generate(data: ReportData): string {
return this.formatter.format(data)
}
}
Constructors for what the class must have, setters for what it can live without. That's close to word for word what the Spring docs suggest. If you catch yourself adding a setter so you don't have to touch a long constructor, the constructor is telling you something about the class.
The composition root: wire everything in one place
Once every class takes its dependencies through the constructor, a new question pops up: who actually calls new? Mark Seemann's answer is the composition root, "a (preferably) unique location in an application where modules are composed together," placed "as close as possible to the application's entry point" (Seemann, Composition Root). For a Node service that's the startup file. For a CLI it's main.
It's the one spot where concrete classes like PostgresOrderRepository get named and constructed. Everything else talks through interfaces.
// composition-root.ts: the one place that knows the concrete classes
import { PostgresOrderRepository } from './adapters/postgres-order-repository'
import { StripePaymentGateway } from './adapters/stripe-payment-gateway'
import { SendGridMailer } from './adapters/sendgrid-mailer'
import { OrderService } from './domain/order-service'
import { OrderController } from './http/order-controller'
export function buildApp(): OrderController {
// 1. Leaves first: adapters that talk to the outside world
const orders = new PostgresOrderRepository(process.env.DATABASE_URL!)
const payments = new StripePaymentGateway(process.env.STRIPE_SECRET_KEY!)
const mailer = new SendGridMailer(process.env.SENDGRID_API_KEY!)
// 2. Services get their collaborators
const orderService = new OrderService(payments, orders, mailer)
// 3. The delivery layer gets the service
return new OrderController(orderService)
}
It reads like a recipe: make the ingredients, combine them into services, put the services behind the controllers. A new teammate who wants to know how the app hangs together opens one file. Swapping SendGrid for another provider means changing one line here and writing one new adapter.
Tests get their own tiny composition root that plugs in fakes:
// in a test file: same service, fake collaborators
const svc = new OrderService(
new InMemoryPaymentGateway(),
new InMemoryOrderRepository(),
new SpyMailer(),
)
// no network, no database, runs in milliseconds
Wiring by hand vs a DI container
Everything so far is DI without a container. Seemann calls it Pure DI, a name he picked to replace the older "Poor Man's DI," which made it sound second-rate (Seemann, Pure DI). For a lot of projects it's the right call: plain code, no hidden steps, a stack trace you can follow, and the compiler tells you when a constructor argument is missing.
A container takes over the wiring. You register which implementation goes with which abstraction, and the container builds the whole object graph and manages how long each object lives. Here's the same service handed to NestJS:
// order.module.ts: the same wiring, handed to NestJS
import { Inject, Injectable, Module } from '@nestjs/common'
export const PAYMENT_GATEWAY = Symbol('PaymentGateway')
@Injectable()
export class OrderService {
constructor(@Inject(PAYMENT_GATEWAY) private readonly payments: PaymentGateway) {}
}
@Module({
providers: [
OrderService,
{ provide: PAYMENT_GATEWAY, useClass: StripePaymentGateway },
],
})
export class OrderModule {}
Notice the Symbol token. TypeScript interfaces vanish at compile time, so the NestJS docs point out that an interface "can't serve as a DI token by itself" and you need a string, a symbol or an abstract class instead (NestJS custom providers). Small detail, and a good reminder that a container is extra machinery with its own rules to learn.
OrderService reaches out and builds its own dependencies, so every arrow is a coupling baked into the class. Right: the composition root builds the concrete objects and passes them in. The arrows flip, and the service only ever sees interfaces.| Question | Pure DI (by hand) | Container (NestJS, ASP.NET Core, Spring, InversifyJS) |
|---|---|---|
| How do you register things? | You write the new calls in the composition root. |
Decorators, tokens or registration calls such as AddScoped in ASP.NET Core. |
| Who builds the graph? | You, in the right order. | The container, recursively, when you ask for the top-level type. |
| Object lifetimes | You decide and you hold the references: one per app, one per request, or new each time. | Declared per registration. ASP.NET Core has singleton, scoped and transient. NestJS has Scope.DEFAULT, Scope.REQUEST and Scope.TRANSIENT. |
| Debugging | Plain code. Breakpoint anywhere, read the stack. | Resolution happens inside the container. "Why did I get this instance?" means learning its rules. |
| Boilerplate | Grows with the graph. Fifty classes means a long wiring file. | Low. The container walks the constructors for you. |
| When mistakes show up | Compile time: a missing argument is a type error. | Often at startup or on first resolve, when a binding turns out to be missing. |
When does a container earn its keep? There's no magic number. A decent signal is that the composition root has become its own chore: you keep forgetting to wire new classes, or you're hand-managing request-scoped objects in several places. If the wiring file still fits on a screen or two, the plain version is easier to read and debug.
The testing payoff: fakes in, fast tests out
This is where most people feel the difference first. When every dependency comes through the constructor, a test is a small composition root with fakes. No database, no network, no vendor sandbox, so the test runs in milliseconds and doesn't fail because a staging account hit its own rate limit.
// order-service.test.ts
import { testCart } from './fixtures'
class InMemoryPaymentGateway implements PaymentGateway {
receipts: Receipt[] = []
async charge(amount: Money, token: string): Promise<Receipt> {
const receipt = { id: 'fake-receipt', amount, token }
this.receipts.push(receipt)
return receipt
}
}
class InMemoryOrderRepository implements OrderRepository {
saved: Order[] = []
async save(order: Order): Promise<void> {
this.saved.push(order)
}
}
class SpyMailer implements Mailer {
sentTo: string[] = []
async send(to: string): Promise<void> {
this.sentTo.push(to)
}
}
it('charges, saves and emails when an order is placed', async () => {
const payments = new InMemoryPaymentGateway()
const orders = new InMemoryOrderRepository()
const mailer = new SpyMailer()
const order = await new OrderService(payments, orders, mailer).placeOrder(testCart)
expect(payments.receipts).toHaveLength(1)
expect(orders.saved).toContainEqual(order)
expect(mailer.sentTo).toContain(testCart.email)
})
The in-memory fake is a test-time adapter, and the real Stripe or Postgres class is the production adapter. That's the same split Ports and Adapters describes at the architecture level. DI is the mechanism that makes the swap possible, while ports and adapters decides where the boundary sits.
There's a SOLID connection too. The "D" is the Dependency Inversion Principle: high-level policy and low-level details should both depend on abstractions. In the code above, OrderService is the policy, StripePaymentGateway is a detail, and PaymentGateway is where they meet. DIP is about which way the source-code arrows point, and DI is how the objects actually get connected at runtime. If the arrows part is the fuzzy bit, Dependency Direction in Plain Language covers it.
One honest caveat: Fowler doesn't buy testing as a reason to prefer DI over a service locator, since both are easy to stub (same article). Fair point. In practice the bigger win for tests is that constructor injection makes the needed fakes obvious from the signature, so nobody has to dig through the code to find out what to stub.
Where DI goes wrong
The idea is simple. There are still a few well-worn ways to undo it.
Service Locator
A service locator is a registry that code calls at runtime to fetch what it needs:
// looks tidy, but the dependencies are hidden again
class OrderService {
async placeOrder(cart: Cart): Promise<Order> {
const payments = ServiceLocator.get<PaymentGateway>('PaymentGateway')
const orders = ServiceLocator.get<OrderRepository>('OrderRepository')
const order = Order.fromCart(cart)
await payments.charge(order.total, cart.paymentToken)
await orders.save(order)
return order
}
}
It feels cleaner than new StripeClient() inline, and creation has moved out of the class. But the signature is back to hiding what the class needs. Seemann calls it an anti-pattern for exactly that reason: the code compiles fine, and only fails at runtime when a registration is missing (Seemann, Service Locator is an Anti-Pattern). The ASP.NET Core docs say the same in one line: "Avoid using the service locator pattern" (Microsoft Learn). Fowler is milder and treats it as a valid option inside your own app. His bigger point is that you separate configuration from use, whichever pattern you pick. For application code most teams land on constructor injection, because the dependencies stay visible.
The ten-argument constructor
When a constructor grows to seven, eight or ten parameters, DI isn't failing you. It's showing you a class with too many jobs. Spring's docs call a large number of constructor arguments "a bad code smell," and Microsoft's guidance links many injected dependencies to a Single Responsibility violation. Split the class into smaller collaborators with short lists. Constructor length makes a decent health check during review.
Reaching for the container from inside a service
Calling the container directly from business code is the service locator again under another name. Seemann's rule is short: "A DI Container should only be referenced from the Composition Root." Services only talk to what they were given.
Magic you can't trace
Decorators and reflection metadata make wiring short, and they also make it hard to follow when something breaks. Lifetimes are the classic trap. In NestJS, a request-scoped provider makes everything that injects it request-scoped too, all the way up the chain, and the docs warn that request scope costs latency (NestJS injection scopes). In ASP.NET Core, injecting a scoped service into middleware through the constructor throws at runtime, because it would force that service to live like a singleton. If you spend more time reading container docs than your own business logic, add an explicit module file that spells out the main bindings, or step back to wiring by hand.
Right-sizing DI as the codebase grows
The goal stays the same at every size: code you can test and change. What changes is how much machinery it takes to get there. Read the left column as signals in your codebase, since team headcount is a rough proxy at best.
| What you see | What to use | Typical shape |
|---|---|---|
| One service, a handful of classes | Pure DI with one composition root. | A single buildApp() of a few dozen lines. Quick to write, easy to read. |
| Several feature areas, one deployable | Still Pure DI, split by feature. | buildOrderModule(), buildBillingModule(), each self-contained and composed once at startup. |
| The wiring file is a chore and request scopes multiply | A container starts paying for itself, often the one your framework already ships. | Registrations per module, request-scoped services for web handlers, a startup check for missing bindings. |
| Framework built around a container | Use the framework's container. NestJS, Spring and ASP.NET Core all have one at the core. | Modules with imports and exports, lifecycle hooks, conventions everyone on the team knows. |
Say a fintech team starts with a thirty-line composition root wiring three services. Two years in, there are sixty, and keeping the wiring straight is a weekly task. Moving to a container at that point is mostly mechanical, because the pattern underneath (constructor injection, interfaces, one place that wires things) hasn't changed. The container does the typing for you. It doesn't change the idea.
Start with constructor injection and a hand-written composition root. If you add a container later, you replace new calls with registrations in one place. Your domain code, services and tests don't need to change.
Key takeaways
- Code gets rigid and hard to test when a class calls
newon its own dependencies. Pass them in instead. - Inversion of Control is the broad principle (a framework calls you). Dependency Injection is the specific pattern for handing objects their collaborators, named by Fowler in 2004.
- Use constructor injection by default and setters only for optional pieces.
- Keep concrete wiring in one composition root near the entry point. Everything else talks through interfaces.
- Pure DI is enough for many apps. A container pays off when wiring and lifetimes become a chore, and it brings its own rules, like tokens for interfaces in NestJS.
- Watch for service locators, ten-argument constructors and container calls outside the composition root.
Something to try this week: grep your services for new inside method bodies, pick one that creates a database or HTTP client, move it to the constructor and write the fast unit test you couldn't write before. Once you know how dependencies flow, the next question is how to lay out the files, which is what Structuring a Codebase: Feature Folders vs Layers covers.