What Is Dependency Injection? Connecting Implementations with Tokens in NestJS
Dependency Injection (DI) is a design approach in which an external assembler or container supplies the collaborators a class needs, instead of the class constructing them or looking them up globally. This article shows how to configure constructor injection in NestJS 11, why a TypeScript interface cannot serve as a runtime injection token, and how to choose provider scope.
Dependency Injection (DI) is a design approach in which an external assembler or container supplies the collaborators a class needs, instead of the class constructing them or looking them up globally. This article shows how to configure constructor injection in NestJS 11, why a TypeScript interface cannot serve as a runtime injection token, and how to choose provider scope.
What do dependency and injection mean?
An object whose capability a class uses is a dependency. If an order service runs new SqlOrdersRepository() itself, it becomes tied to that implementation and its construction. With DI, the service declares the contract it needs, and a separate composition point connects and supplies a matching implementation. (Martin Fowler: Dependency Injection)
Inversion of Control (IoC) is broader: a framework or assembler takes responsibility for some program flow or object assembly that application code might otherwise control. DI is one way to provide objects. Service Locator is a distinct pattern in which an object looks up dependencies in a central registry. Both can decouple implementation choice, but DI can make required dependencies visible in the constructor. (Martin Fowler: Dependency Injection)
Why use constructor injection?
Constructor injection passes dependencies as constructor parameters when an object is created. The constructor makes required collaborators visible, and the object can be set up so it is not used before those collaborators are supplied. It also helps distinguish required dependencies from optional settings that may change later. (Martin Fowler: Dependency Injection forms)
NestJS can use a class provider as a token and inject it into a constructor. The provider must be registered in the module where it is used. For cross-module use, align the exporting and importing module boundaries. (NestJS: Providers, NestJS: Modules)
How do you register an interface dependency in NestJS?
TypeScript interfaces and type aliases do not remain at runtime after compilation. Nest therefore cannot resolve a provider from an interface name such as OrdersRepository alone. Keep the interface as a static type contract, register a runtime token such as a string or Symbol, and specify it with @Inject(). This example uses a logger contract to show the binding. (NestJS: Custom providers)
import { Inject, Injectable, Module } from '@nestjs/common';
export const APP_LOGGER = Symbol('APP_LOGGER');
export interface Logger {
log(message: string): void;
}
@Injectable()
export class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
@Injectable()
export class AuditService {
constructor(@Inject(APP_LOGGER) private readonly logger: Logger) {}
record(event: string): void {
this.logger.log(`audit: ${event}`);
}
}
@Module({
providers: [
AuditService,
{ provide: APP_LOGGER, useClass: ConsoleLogger },
],
exports: [AuditService],
})
export class AuditModule {}Registration and injection must use the same APP_LOGGER Symbol object. Creating a second Symbol('APP_LOGGER') produces a different runtime token even though its description matches. A class can also be the token, or an abstract class can serve as both contract and runtime token. Choose useClass to select an implementation, useValue for an existing object or constant, or useFactory when construction needs a function. (NestJS: Custom providers)
This code illustrates configuration; it was not run or build-verified. In an application, split files as needed and register providers in modules. To use AuditService from another module, import AuditModule. The snippet does not configure an external logger, secrets, or application settings.
How do singleton and request-scoped providers differ?
NestJS providers are singleton-scoped by default: one instance is shared across the application, which is appropriate for most providers. REQUEST creates an instance for each incoming request; TRANSIENT gives each consumer a separate instance. Consider request scope only when per-request state truly belongs on the instance. (NestJS: Injection scopes)
Request scope can bubble up to dependent providers and controllers. NestJS notes that it can add performance cost and recommends the default singleton unless request scope is needed. Do not store request data in fields on a shared service just because the data is request-specific; pass it as a method argument or use the framework's request-context mechanism. (NestJS: Injection scopes)
What should you check when injection fails or dependencies form a cycle?
Confirm the provider token and the value passed to `@Inject()` are the same runtime value. An interface cannot itself be the token.
Confirm the provider is listed in the module's `providers`. For another module's provider, check that it is exported there and the consumer imports that module.
Use a `Symbol` to reduce collisions when unrelated providers might share a string token; reuse the same exported constant for registration and injection.
Check for a cycle such as A injecting B while B injects A. First see whether responsibilities or module boundaries can be refactored. If a cycle is unavoidable, consider NestJS `forwardRef()` or `ModuleRef`; do not use them as the default cover for a design problem.
Check provider scope. A request-scoped dependency can propagate its scope up the injection graph.
Check whether barrel files (`index.ts`) create circular imports between providers or modules in the same directory. ([NestJS: Circular dependency](https://docs.nestjs.com/fundamentals/circular-dependency))