Dependency Injection Without the Framework
Dependency injection is a practice, not a container. How constructor injection, composition roots, and manual wiring give you the benefits without the indirection.
By Velloreth
Dependency injection is a practice, not a product. The practice: a unit of code does not construct the things it needs, it receives them from whoever creates it. The product — a container with annotations, reflection, and configuration — is one optional way to automate that, and for a lot of codebases it adds more indirection than it removes.
This is about doing the practice with plain constructors and one wiring file, and knowing exactly when a framework starts earning its keep.
What is actually being injected
Every non-trivial unit depends on collaborators: a repository, a payment gateway, a logger, a clock, a UUID generator. The question is not whether those dependencies exist, but where they get decided.
// hard-wired: the class decides its own world
class OrderService {
private repo = new PostgresOrderRepo(); // concrete, always
private clock = new SystemClock(); // real time, untestable
}
// injected: the caller decides, the class only uses
class OrderService {
constructor(
private repo: OrderRepo,
private clock: Clock,
) {}
}
The second version does three things for you. Its dependencies are visible in the signature. Its tests can pass an in-memory repo and a frozen clock without touching globals. And swapping Postgres for a queue-backed store is an edit in one place, not a search across the codebase.
The dependency count is a design signal, too. A constructor with two parameters says “small, focused unit.” A constructor with nine says the unit is doing three jobs, and no container will fix that.
The spectrum you are choosing from
| Approach | How wiring works | Cost |
|---|---|---|
new inline everywhere | Each class constructs collaborators | Hidden graph; untestable; scattered decisions |
| Manual constructor injection | Callers construct and pass dependencies | Explicit; some boilerplate |
| Composition root + manual wiring | One entrypoint file builds the graph | Boilerplate concentrated in one file |
| DI container | Framework resolves and injects | Dynamic; adds indirection and a learning curve |
| Service locator | Classes ask a global registry for anything | Dependencies invisible; effectively hidden new |
Most teams are better off at row three than row four. The container’s real features — automatic graph resolution, lifetime management, dynamic plugin registration — solve problems you may never have. Its real costs arrive immediately: your application’s structure now lives in configuration and annotations instead of code you can read top to bottom.
Constructor injection, consistently
One rule covers most of the practice: take dependencies through the constructor, store them as immutable fields, never fetch anything mid-method.
class InvoiceService {
constructor(
private readonly invoices: InvoiceRepo,
private readonly mailer: Mailer,
private readonly clock: Clock,
private readonly logger: Logger,
) {}
async issue(orderId: string): Promise<Invoice> {
const order = await this.invoices.findOrder(orderId);
if (!order) throw new NotFoundError(orderId);
const invoice = Invoice.from(order, this.clock.now());
await this.invoices.save(invoice);
await this.mailer.send(invoice.emailMessage());
this.logger.info("invoice.issued", { id: invoice.id });
return invoice;
}
}
Four things worth noting:
- No
new Mailer()insideissue(). The moment a method constructs a collaborator, you have a hidden dependency that tests cannot reach. - Property injection (
service.mailer = ...after construction) creates objects that are valid but broken: constructed without a required dependency, they throw at call time instead of construction time. Constructors that enforce required inputs are the entire point. - Optional dependencies are a design smell. If something is truly optional, model it as a nullable strategy the caller passes —
notifier?: Notifierwith an explicit null object — rather than a dependency the class sometimes looks up. - Return values and parameters are also dependencies. If
issue()reaches into a global config to decide a tax rate, that config is a dependency you did not declare.
The composition root
The composition root is the one place where concrete implementations get chosen: your entrypoint, main, or bootstrap module. Everything below it programs against abstractions.
// main.ts — the only file that mentions concrete classes
const pool = new PgPool(process.env.DATABASE_URL);
const repo = new PostgresOrderRepo(pool);
const mailer = new SmtpMailer(process.env.SMTP_URL);
const clock = new SystemClock();
const logger = new ConsoleLogger("orders");
const orders = new OrderService(repo, mailer, clock, logger);
createServer(orders).listen(3000);
Rules that keep this working:
- One root per process. Tests build their own small roots — that is all a test fixture is.
- Narrow modules compose upward. A module exports a factory (
createOrderService(deps)), not a singleton. Whoever needs it passes dependencies down. - No reaching back up. If a repository needs config, the root reads config and passes a value. The repo never imports the environment itself.
- No ambient state. Singletons, module-level mutable registries, and
Container.get()called from business code all reintroduce the hidden graph you just removed.
This is also where you handle the boring decisions once: retry policy, timeouts, connection pooling, log level. Instead of every class deciding its own, the root decides and hands over ready-made objects.
Lifetimes without a container
Containers formalize object lifetimes (transient, scoped, singleton), but manual wiring makes them visible instead of implicit:
| Lifetime | Manual pattern | Watch out for |
|---|---|---|
| Per-call (transient) | Construct inside the request handler | Rebuilding expensive objects per call |
| Per-request (scoped) | Handler creates one graph, passes it down | Sharing a scoped object past the request |
| Application (singleton) | Composition root creates it once | Hidden state; test leakage |
| Per-test | Test fixture creates a fresh graph | Accidentally sharing fixtures across tests |
The classic bug here is a singleton holding request state: one UserContext shared across requests turns into cross-user data leaks under concurrency. The manual fix is structural — if an object sees per-request data, it gets constructed per request, and the signature says so.
Cycles, and the shape of the graph
Manual wiring surfaces structural problems that containers happily hide, and the most common one is the dependency cycle: A needs B, B needs C, C needs A. A container may resolve it (or throw at startup); new expressions simply produce a compile error or a null — which is information, not a limitation.
The cycle is telling you something real. Almost always one of these is true:
- Two things are one thing.
OrderServiceandPaymentServiceconstantly coordinating suggests a missing concept between them — aCheckoutorchestration or a domain event that both react to. - One direction is wrong. The dependency should flow the other way: define an interface on the side that needs the abstraction, and let the concrete side implement it (dependency inversion, in the strict sense).
- A callback is missing. Instead of A calling B which calls back into A, A accepts
onPaid: (order) => voidand the root wires the listener. The graph becomes a DAG again, and the root is exactly the right place to know who listens to what.
Resist the three escape hatches that make cycles “work”: lazy getters that hide the construction order, global singletons that any file can reach into, and service locators (Container.get(X) mid-method). Each one converts a structural error into a runtime surprise.
A related habit that keeps manual graphs manageable: pass parameter objects when a signature grows past three or four dependencies. Not to hide them — name them honestly:
interface OrderServiceDeps {
repo: OrderRepo;
mailer: Mailer;
clock: Clock;
logger: Logger;
metrics: Metrics;
}
new OrderService({ repo, mailer, clock, logger, metrics });
This does not make the dependency list shorter; it makes the call site readable and gives you one place to extend when a fifth collaborator appears. It also plays well with test fixtures — a test builds a partial deps object and overrides only what the case needs.
Interfaces: only where a decision is hidden
Constructor injection does not require an interface per dependency. Abstraction earns its place when it hides a choice:
- A
PaymentGatewayyou may switch between Stripe and a sandbox — yes, abstract it. - A
StringFormatterwith one implementation — no, depend on the concrete class and abstract when a second implementation actually arrives.
The rule of thumb: abstract at the seams your system genuinely varies — external services, storage, time, randomness, anything a test must replace. Everything else is interface ceremony that makes navigation harder and refactors noisier.
// worth abstracting: tests must control it, production must swap it
interface Clock { now(): Date }
class FrozenClock implements Clock {
constructor(private t: Date) {}
now() { return this.t; }
}
Time is the canonical example precisely because everything depends on it and nothing should call Date.now() directly inside business logic.
Testing is the dividend
The reason to bother is not architecture aesthetics — it is what the tests look like:
describe("InvoiceService.issue", () => {
it("does not send mail when the invoice already exists", async () => {
const repo = new InMemoryOrderRepo([existingOrder]);
const mailer = new RecordingMailer(); // captures, never sends
const clock = new FrozenClock(new Date("2026-03-12T10:00:00Z"));
const svc = new InvoiceService(repo, mailer, clock, noopLogger());
await expect(svc.issue(orderId)).rejects.toThrow(AlreadyIssuedError);
expect(mailer.sent).toHaveLength(0);
});
});
No database, no network, no clock-skew flakiness, no patching of module internals. The test constructs exactly the world it needs. Compare that with testing a class that news its own SMTP client: you are now mocking module registries, fighting import order, and writing tests that break when someone moves an import.
Two supporting habits make the payoff stick:
- Depend on behavior, not construction. Tests assert
mailer.sentandinvoice.dueDate, neversvc.mailer instanceof SmtpMailer. - Make invalid states unrepresentable in fixtures. An
InMemoryOrderRepothat validates on insert catches contract drift the same way production would.
When a container is actually justified
Manual wiring has a ceiling. You have crossed it when:
- The root file sprawls past a screen or two of repetitive assembly. At that point the boilerplate is the maintenance cost, and a container that registers types and resolves them is a net simplification.
- Wiring is genuinely dynamic. Plugin systems, multi-tenant apps that build per-tenant graphs, or dependency sets chosen at runtime — this is the case containers were designed for.
- Multiple implementations must be resolved by key.
Map<HandlerType, Handler>gets you far; when the registry, ordering, and lifetimes all interact, a container formalizes it. - The graph is wide and deep enough that manual lifetime tracking becomes error-prone — several request-scoped objects depending on shared singletons in more than one layer.
Even then, keep the boundary: the container lives in the composition root. Business classes still take constructor parameters. If a service method starts taking a Resolver or a Provider<T> so it can pull dependencies on demand, you have traded a visible graph for a service locator — the same hidden coupling, wearing a framework’s logo.
A good middle ground exists in most languages: lightweight “poor man’s DI” — small factory functions, a tiny registry, or a module that exports configured instances. You get centralized wiring with zero magic, and the indirection is something you can read in one sitting.
The shape to aim for
The end state is unremarkable, which is the point:
- Dependencies arrive through constructors, visible at every call site.
- One file per process decides concretions.
- Tests build small graphs of fakes in a few lines.
- No global registry, no reflection, no annotation scanning.
- A container appears only when manual wiring measurably hurts — and even then, only at the root.
Frameworks solve a real problem. Just make sure it is your problem first: count how many objects your application actually constructs, look at how many of them need a second implementation or a test double, and let that number — not habit — decide whether you need anything more than a constructor and a main function.