Skip to Content
Mengty Learns
Design

Dependency Injection in TypeScript

Constructor injection by hand vs DI containers, testing with in-memory fakes, why Service Locator is an anti-pattern, and when DI is overkill.

explanationintermediateTested with typescript 7.0.2Updated Nov 26, 2026

TL;DR

Dependency Injection means passing collaborators in from the outside instead of calling new PostgresRepo() inside business logic. In TypeScript, constructor injection by hand (Pure DI) gives you compile-time safety and fast tests with in-memory fakes—without needing a reflection-based DI container or a Service Locator.

Why it exists

If DeployService creates its own new PostgresAuditLog() and new Date() internally, every unit test needs a running database and wall-clock hacks. Worse, you cannot swap implementations per environment without editing DeployService.

Mental model

Compare the three ways dependencies get resolved:

ApproachHow dependencies are obtainedCompile-time safetyHidden dependencies?Best for
Pure DI (by hand)Passed via constructor or function args from main.tsFull (tsc checks every arg)No—signature lists all depsMost TypeScript apps & libraries
DI ContainerFramework resolves graph via decorators/tokensPartial (runtime token errors possible)MediumHuge enterprise apps with 100+ wired services
Service LocatorClass calls global Locator.get(Key) internallyWeak (fails at runtime)Yes—hidden from callers & testsLegacy codebases only (anti-pattern)

Do it

1. Constructor injection by hand (Pure DI)

Define small interfaces for external I/O, inject them in the constructor, and wire concrete implementations once at your entry point:

interface AuditLog {
  record(action: string, at: Date): Promise<void>;
}

interface Clock {
  now(): Date;
}

class DeployService {
  constructor(
    private readonly audit: AuditLog,
    private readonly clock: Clock,
  ) {}

  async promote(version: string): Promise<void> {
    await this.audit.record(`promote:${version}`, this.clock.now());
  }
}

// Production wiring in main.ts (composition root)
class ConsoleAuditLog implements AuditLog {
  async record(action: string, at: Date): Promise<void> {
    console.log(`[audit ${at.toISOString()}] ${action}`);
  }
}

const prodService = new DeployService(new ConsoleAuditLog(), { now: () => new Date() });

2. Testing with in-memory fakes

Because DeployService depends only on AuditLog and Clock, tests pass lightweight fakes with zero mocking frameworks:

class FakeAuditLog implements AuditLog {
  readonly entries: Array<{ action: string; at: Date }> = [];
  async record(action: string, at: Date): Promise<void> {
    this.entries.push({ action, at });
  }
}

const fakeAudit = new FakeAuditLog();
const fixedClock: Clock = { now: () => new Date('2026-11-26T00:00:00Z') };
const svc = new DeployService(fakeAudit, fixedClock);

await svc.promote('v2.1.0');
// Assert fakeAudit.entries has 1 entry at 2026-11-26T00:00:00Z

3. The Service Locator anti-pattern (avoid)

A Service Locator looks convenient at first because constructors stay empty, but it hides dependencies and breaks at runtime:

// Anti-pattern: caller has no idea DeployService needs 'auditLog'
class BadDeployService {
  async promote(version: string): Promise<void> {
    const audit = ServiceLocator.get<AuditLog>('auditLog'); // throws if unregistered!
    await audit.record(`promote:${version}`, new Date());
  }
}

4. Pure DI vs DI containers

DI containers (using reflect-metadata or token registries) automate wiring when an app has dozens of scoped/transient services. In TypeScript, however, containers add runtime magic, decorator config, and startup errors when a binding is missing—whereas Pure DI in a single buildApp() function is 100% type-checked by tsc.

When NOT to use it

Overengineering happens when you inject pure deterministic helpers (like Math, JSON, or a stateless formatBytes() function) through constructor interfaces, or install a heavyweight DI container for a 10-file CLI or API. Only inject impure boundaries (databases, HTTP clients, clocks, queues) or behavior that genuinely varies between prod and tests.

Real-world example in this stack

In Hexagonal Architecture, domain services accept inbound/outbound ports via constructor injection so tests can swap PostgresOrderRepo for InMemoryOrderRepo without touching a database. Similarly, this site's React components receive data and callbacks as props rather than reading global singletons.

Gotchas

  • Constructor bloat (too many parameters): If a class takes 7+ injected dependencies, it is usually violating the Single Responsibility Principle—split the class instead of reaching for a DI container to hide the smell.
  • Mocking concrete classes instead of using fakes: Heavy jest.fn()/vi.fn() mocks that mirror internal SQL queries make tests brittle; a simple InMemoryRepo implementing the interface is faster and more realistic.
  • Confusing Dependency Injection with Dependency Inversion: DI is the technique of passing dependencies in; DIP (the D in SOLID) is the principle that high-level policy owns the interface.

Production checklist

  • Wire concrete implementations in one composition root (main.ts / buildContainer.ts), never inside domain classes.
  • Inject impure boundaries (DB, network, clock, filesystem), not pure utility functions.
  • Prefer Pure DI (explicit TypeScript constructors/functions) until the wiring file genuinely outgrows manual maintenance.

Check yourself

Check Yourself

1. Why is the Service Locator pattern widely considered an anti-pattern compared to constructor injection?

2. Which dependencies should you actually inject in TypeScript rather than import directly?

Sources