Skip to content
Back to blog
Design Patterns

Dependency Injection: Separating Construction from Usage

Updated 17 min read

Dependency Injection is more than passing objects through constructors. Learn how to separate construction from usage, distinguish DI from the Dependency Inversion Principle, manage dependency lifecycles, and decide when a DI container is worth the complexity.

Table of Contents

Introduction

Every application depends on other components.

A service may need a database repository. A payment processor may need an external API client. A background worker may need a message publisher. These dependencies are part of how the application performs its work.

The problem is not that dependencies exist. The problem is how components obtain them.

Consider a simple order service:

typescript
class OrderRepository {
  async save(orderId: string): Promise<void> {
    // Persist the order.
  }
}

class OrderService {
  private readonly repository = new OrderRepository();

  async createOrder(orderId: string): Promise<void> {
    await this.repository.save(orderId);
  }
}

This code is straightforward. The service creates its repository and uses it.

For a small application, that may be perfectly acceptable.

However, the service now controls two things: its business behavior and the construction of its dependency. If the repository later requires a database connection, configuration, logging, or a different implementation for testing, the service may need to change even though its business behavior has not changed.

The problem becomes more noticeable when dependencies are nested.

An order service creates a repository. The repository creates a database client. The database client reads configuration and initializes a connection pool. Another service independently repeats some of the same construction logic.

Eventually, understanding what a service needs also requires understanding how its entire dependency graph is constructed.

Dependency Injection offers a different approach.

Instead of constructing its own dependencies, a component receives the dependencies it needs from the outside.

The idea is simple, but its consequences reach much further than constructor syntax.

Dependency Injection separates the responsibility of using a dependency from the responsibility of providing it.

This article explores why that separation matters, how to implement it in TypeScript, how it relates to the Dependency Inversion Principle, and when a DI container is actually necessary.

1. The Problem: Components Control Their Own Dependencies

Return to the original implementation:

typescript
class OrderService {
  private readonly repository = new OrderRepository();

  async createOrder(orderId: string): Promise<void> {
    await this.repository.save(orderId);
  }
}

The service works, but its dependency is fixed inside the class.

Suppose we want to test order creation without connecting to a real database. We might introduce an in-memory repository, but the service has no straightforward way to receive it.

We could add conditional construction logic:

typescript
class OrderService {
  private readonly repository: OrderRepository;

  constructor(useInMemoryRepository: boolean) {
    this.repository = useInMemoryRepository
      ? createInMemoryRepository() as OrderRepository
      : new OrderRepository();
  }
}

This is a step in the wrong direction.

The service now knows about multiple implementations, how to construct them, and when to select them. Testing concerns and infrastructure decisions are leaking into the component's business responsibility.

A more scalable question is:

Why should OrderService decide which repository implementation it uses at all?

Its responsibility is to create orders. It needs a repository capable of saving data, but it does not necessarily need to know whether that repository uses PostgreSQL, an in-memory store, or another persistence mechanism.

That distinction gives us the first design principle:

A component should know what it needs from a dependency without necessarily owning how that dependency is constructed.

2. The Core Idea Behind Dependency Injection

Dependency Injection moves dependency construction outside the component that consumes the dependency.

First, define the contract:

typescript
interface OrderRepository {
  save(orderId: string): Promise<void>;
}

Then implement it:

typescript
class PostgresOrderRepository implements OrderRepository {
  async save(orderId: string): Promise<void> {
    // Persist the order using PostgreSQL.
  }
}

The service receives the repository through its constructor:

typescript
class OrderService {
  constructor(
    private readonly repository: OrderRepository,
  ) {}

  async createOrder(orderId: string): Promise<void> {
    await this.repository.save(orderId);
  }
}

The service no longer constructs its own repository. It declares the dependency it needs and receives an implementation from its caller.

The application can assemble the components at the composition boundary:

typescript
const repository = new PostgresOrderRepository();
const orderService = new OrderService(repository);

await orderService.createOrder("order-123");

This example uses manual dependency injection. No framework or container is required.

What actually changed?

The business behavior remains the same: the service saves an order through a repository.

What changed is the ownership of construction.

Before injection, OrderService both created and used its repository. After injection, the code that assembles the application decides which repository to provide.

This creates a useful separation between two responsibilities:

  • Application behavior: What the service does with its dependencies.
  • Application composition: Which implementations are created and how they are connected.

This boundary becomes increasingly valuable when applications have multiple environments, alternative implementations, integration tests, or complex dependency graphs.

Injection does not automatically mean abstraction

A component can receive a concrete dependency:

typescript
class OrderService {
  constructor(
    private readonly repository: PostgresOrderRepository,
  ) {}
}

This is still Dependency Injection because the repository is supplied from outside.

However, the service remains coupled to the concrete implementation's type. Replacing it with an in-memory repository may require changing the constructor or creating a compatible subclass.

Injecting an interface or another stable contract can reduce that coupling, but the two decisions are distinct:

  • Dependency Injection determines how a dependency is supplied.
  • Abstraction determines what the consuming component depends on.

Using both is often helpful, but neither concept should be confused with the other.

3. Three Ways to Inject Dependencies

Dependency Injection is a design technique, not a requirement to use constructor parameters in every situation.

The appropriate method depends on the dependency's role and lifecycle.

Constructor injection

Constructor injection supplies required dependencies when an object is created.

typescript
class OrderService {
  constructor(
    private readonly repository: OrderRepository,
  ) {}
}

This is usually the best default for required dependencies.

The object cannot be constructed without providing the repository. Its requirements are explicit, and the dependency can be stored in a readonly property.

Constructor injection also makes it easy to create different configurations for production and testing.

Setter injection

Setter injection provides a dependency after the object has been created.

typescript
class ReportService {
  private exporter?: ReportExporter;

  setExporter(exporter: ReportExporter): void {
    this.exporter = exporter;
  }

  async exportReport(reportId: string): Promise<void> {
    if (!this.exporter) {
      throw new Error("Report exporter has not been configured");
    }

    await this.exporter.export(reportId);
  }
}

This can be useful when a dependency is genuinely optional or must be changed after construction.

However, it introduces a possible invalid state: the service exists before its required exporter is configured.

For mandatory dependencies, constructor injection is usually safer because it makes incomplete construction harder.

Method injection

Method injection supplies a dependency only for a particular operation.

typescript
interface Clock {
  now(): Date;
}

class ReportService {
  generateReport(clock: Clock): string {
    return `Generated at ${clock.now().toISOString()}`;
  }
}

Here, the clock is needed for the operation rather than necessarily for the lifetime of the service.

Method injection can be useful for operation-specific collaborators or values that vary per call. However, frequently passing the same dependency through many methods may indicate that it belongs in the constructor instead.

Which method should you choose?

Use constructor injection for dependencies required by the object as a whole. Consider method injection when a collaborator is genuinely specific to one operation. Use setter injection only when delayed configuration or replacement is an intentional part of the design.

The objective is not to maximize the number of injected dependencies. It is to make each component's requirements explicit and its lifecycle understandable.

4. Dependency Injection vs. Dependency Inversion Principle

These concepts are related, but they are not interchangeable.

Dependency Injection is a technique for supplying dependencies.

The Dependency Inversion Principle (DIP) is a design principle about the direction of dependencies.

DIP states that high-level modules should not depend directly on low-level modules. Both should depend on abstractions. Those abstractions should not depend on details; details should depend on abstractions.

Consider this implementation:

typescript
class PostgresOrderRepository {
  async save(orderId: string): Promise<void> {
    // Persist through PostgreSQL.
  }
}

class OrderService {
  constructor(
    private readonly repository: PostgresOrderRepository,
  ) {}

  async createOrder(orderId: string): Promise<void> {
    await this.repository.save(orderId);
  }
}

The repository is injected, but the service still depends on the concrete PostgreSQL repository.

Dependency Injection is present. The dependency direction has not necessarily been inverted.

Now introduce an abstraction owned by the application:

typescript
interface OrderRepository {
  save(orderId: string): Promise<void>;
}

The service depends on the contract:

typescript
class OrderService {
  constructor(
    private readonly repository: OrderRepository,
  ) {}

  async createOrder(orderId: string): Promise<void> {
    await this.repository.save(orderId);
  }
}

The infrastructure implementation satisfies that contract:

typescript
class PostgresOrderRepository implements OrderRepository {
  async save(orderId: string): Promise<void> {
    // Persist through PostgreSQL.
  }
}

The composition boundary connects the implementation to the service:

typescript
const repository: OrderRepository =
  new PostgresOrderRepository();

const orderService = new OrderService(repository);

The application service now relies on a stable contract rather than the PostgreSQL implementation.

This makes it possible to substitute another implementation without changing the service's business code.

Why does dependency direction matter?

The value becomes clearer when infrastructure changes.

If the application moves from PostgreSQL to another persistence mechanism, the business service should not need to learn the new driver's API or connection setup. Those details should remain within the infrastructure boundary.

However, introducing an interface for every class does not automatically improve architecture.

An abstraction is useful when it creates a meaningful boundary: one that isolates volatility, supports alternative implementations, or makes ownership clearer.

Dependency Injection is one way to connect components. Dependency Inversion helps determine which dependencies those components should have in the first place.

5. Manual Dependency Injection vs. DI Containers

Once a component receives its dependencies, someone must construct the objects and connect them.

For a small application, manual composition is enough:

typescript
const repository = new PostgresOrderRepository();
const orderService = new OrderService(repository);
const controller = new OrderController(orderService);

This is explicit, easy to trace, and requires no additional infrastructure.

As the application grows, the dependency graph may become more complicated:

flowchart TD
    OrderController --> OrderService
    OrderService --> OrderRepository
    OrderRepository --> DatabaseClient
    DatabaseClient --> ConnectionPool

Other services may share the same database client, logger, cache, or API client. Some dependencies may need one shared instance, while others should be created for each request or job.

Manually constructing everything is still possible, but the composition code can become large and repetitive.

A Dependency Injection container automates some of this work.

What does a DI container do?

Depending on the framework, a container may:

  • Register implementations under tokens or identifiers.
  • Resolve dependencies recursively.
  • Manage singleton, request-scoped, or transient lifetimes.
  • Support environment-specific bindings.
  • Detect certain missing dependencies or dependency cycles.

For example, a framework-specific container might register a repository and resolve the service:

typescript
container.register(
  "OrderRepository",
  () => new PostgresOrderRepository(),
);

container.register(
  "OrderService",
  () => new OrderService(
    container.resolve<OrderRepository>("OrderRepository"),
  ),
);

const orderService = container.resolve<OrderService>("OrderService");

This is illustrative pseudocode rather than an implementation for a particular DI library. Real containers have different registration APIs, token rules, and lifecycle semantics.

The important point is that the container takes responsibility for some of the composition work.

When is a container worth introducing?

A container becomes useful when dependency resolution, lifecycle management, or registration rules have become difficult to manage manually.

It is not required merely because a project uses interfaces or constructor injection.

For a small service with a few dependencies, manual composition is often easier to understand than a framework-specific container.

For a large application with many shared infrastructure clients and explicit lifecycle requirements, a container may reduce repetitive wiring and make configuration more consistent.

The hidden cost of containers

Containers introduce their own abstraction.

If dependencies are registered dynamically and resolved through string tokens or decorators, the relationship between components may become harder to follow in an editor or during debugging.

Misconfigured scopes can also cause bugs. For example, a long-lived singleton that captures request-specific state may accidentally retain data across requests.

A container does not eliminate the need to understand the dependency graph. It changes how that graph is expressed and resolved.

Prefer explicit registration and clear lifecycle rules. Avoid using a container as a global service locator that any component can query whenever it needs something.

6. Managing the Dependency Graph

Dependency Injection is often discussed in terms of passing constructor parameters, but the larger concern is the dependency graph.

A dependency graph describes which components require which other components.

As a simplified example:

flowchart TD
    OrderController --> OrderService
    OrderService --> PaymentService
    OrderService --> OrderRepository
    PaymentService --> PaymentGateway
    OrderRepository --> DatabaseClient

A composition root is the part of the application where these dependencies are assembled.

In a small application, it may be a bootstrap file. In a larger application, it may be a framework's module configuration or DI container setup.

Keeping construction near this boundary makes it easier to answer questions such as:

  • Which database implementation does the application use?
  • How are external clients configured?
  • Which dependencies are shared?
  • Where should a test substitute a fake implementation?
  • Which objects are created once, and which are created per request?

Dependency lifetimes matter

Consider a database connection pool. Creating a new pool every time a service is instantiated is usually not the intended lifecycle.

A shared database client may be created once and supplied to multiple repositories. A request-specific context, on the other hand, should not necessarily be shared across unrelated requests.

Dependency Injection does not dictate these lifetimes. It makes it easier to manage them deliberately.

A useful design separates three concerns:

  1. Construction: How is the object created?
  2. Composition: Which components receive it?
  3. Lifecycle: How long does the instance live, and who is responsible for cleanup?

These concerns are related, but they should not be collapsed into one vague idea of “using DI.”

Avoid circular dependencies

A dependency graph should ideally have a clear direction.

If OrderService depends on PaymentService, and PaymentService also depends on OrderService, the components may be tightly coupled through a cycle.

A DI container may report a circular dependency, but resolving the error mechanically does not necessarily fix the design.

Consider whether the two components have mixed responsibilities, whether a third component should coordinate the workflow, or whether one dependency can be replaced with a narrower contract.

A cycle is not always impossible to support, but it is a signal worth investigating.

7. Testing with Dependency Injection

One of the clearest benefits of Dependency Injection is the ability to replace infrastructure dependencies in tests.

Suppose the production service uses a PostgreSQL repository:

typescript
interface OrderRepository {
  save(orderId: string): Promise<void>;
}

class OrderService {
  constructor(
    private readonly repository: OrderRepository,
  ) {}

  async createOrder(orderId: string): Promise<void> {
    await this.repository.save(orderId);
  }
}

A test can provide an in-memory implementation:

typescript
class InMemoryOrderRepository implements OrderRepository {
  readonly savedOrderIds: string[] = [];

  async save(orderId: string): Promise<void> {
    this.savedOrderIds.push(orderId);
  }
}

Then:

typescript
const repository = new InMemoryOrderRepository();
const service = new OrderService(repository);

await service.createOrder("order-123");

if (!repository.savedOrderIds.includes("order-123")) {
  throw new Error("Expected order to be saved");
}

The test verifies the service's interaction with its repository without starting a database.

In a production test suite, a test framework would provide the assertion and test isolation.

Does every dependency need an interface for testing?

No.

Interfaces are useful when the dependency represents a meaningful boundary. They should not be introduced automatically for every class just to make mocking possible.

A concrete, deterministic utility may be simpler to use directly. Some dependencies are best tested through their real implementation, while infrastructure integrations often benefit from a narrower contract.

Also, replacing every dependency with a mock can produce tests that verify implementation details rather than meaningful behavior.

Dependency Injection makes substitution possible. Good test design determines when substitution is useful.

8. Common Dependency Injection Mistakes

Injecting everything indiscriminately

A class does not need a separate abstraction for every function call.

If an operation is a pure calculation or a stable internal helper, introducing a service interface may add complexity without improving flexibility.

Inject dependencies that represent meaningful collaborators, external boundaries, or behaviors that need independent configuration.

Using a global service locator

Consider this pattern:

typescript
class OrderService {
  async createOrder(orderId: string): Promise<void> {
    const repository =
      globalContainer.resolve<OrderRepository>("OrderRepository");

    await repository.save(orderId);
  }
}

The service appears to have no dependencies in its constructor, but it still depends on the container and on a particular registration.

Its requirements are hidden. Tests must also configure the global container correctly.

A service locator may be useful in limited infrastructure or plugin scenarios, but ordinary business services are usually easier to understand when their required dependencies are explicit.

Confusing injection with loose coupling

Passing a concrete implementation through a constructor does not automatically create a flexible architecture.

typescript
class OrderService {
  constructor(
    private readonly repository: PostgresOrderRepository,
  ) {}
}

The dependency is injected, but the service still depends on a specific implementation.

Use an abstraction when it provides a meaningful boundary, not as a purely cosmetic step.

Ignoring lifecycle and resource cleanup

A container may create a shared HTTP client, database pool, or other resource-heavy object. If the application does not manage shutdown and cleanup properly, those resources may outlive their intended scope.

Know which components own resources and which components merely use them.

Turning the composition root into business logic

The composition root should decide how the application is assembled, not become the place where all business decisions are implemented.

Keep business rules inside appropriate application or domain components. Use composition code to connect those components to their dependencies.

Introducing a container too early

A project with five components and straightforward constructors may not need a DI framework.

A container is an additional system to configure, understand, and maintain. Introduce it when the dependency graph or lifecycle requirements justify that cost.

9. When Dependency Injection Is Not Necessary

Dependency Injection is valuable, but it is not a rule that every dependency must be injected.

Consider a small utility:

typescript
function normalizeEmail(email: string): string {
  return email.trim().toLowerCase();
}

There is no meaningful reason to inject this function into every consumer. It has no external resource, no lifecycle, and no alternative implementation that the application needs to select.

Similarly, direct construction may be perfectly appropriate for a small, stable object:

typescript
const formatter = new DateFormatter();

If creating the object is cheap and the concrete implementation is not a source of coupling, introducing a factory or DI container may make the code harder to follow.

Dependency Injection is most valuable when it separates responsibilities that change independently or makes important dependencies explicit.

It is less useful when it only adds indirection around stable, simple behavior.

The objective is not to maximize injection. It is to make component boundaries and dependency ownership clear.

Summary

Dependency Injection is a technique for separating a component's behavior from the construction of its dependencies.

It allows components to declare what they need while leaving the application composition boundary responsible for providing the appropriate implementations.

The most important distinctions are:

  • Dependency Injection: A technique for supplying dependencies from outside a component.
  • Dependency Inversion Principle: A design principle that guides dependency direction toward abstractions.
  • DI Container: A mechanism that automates dependency registration, resolution, and sometimes lifecycle management.
  • Composition Root: The place where an application connects its components and their dependencies.

These concepts work together, but none automatically guarantees good architecture.

Start with constructor injection and manual composition. Introduce meaningful abstractions where they reduce coupling. Add a DI container when the dependency graph, configuration, or lifecycle management becomes difficult to maintain by hand.

A good dependency design makes it clear what a component needs, why it needs it, and where that dependency comes from—without forcing the component to manage concerns outside its responsibility.

  • Design Patterns
  • Dependency Injection
  • OOP
  • Programing
  • Software Architecture
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 17 min read

Unit of Work: Coordinating Data Changes

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.