Skip to the content

Lesson 208 of 296

Dependency injection and the lifecycle

What you will learn

  • What dependency injection is, from zero
  • Inversion of control and the IoC container
  • How Nest resolves dependencies
  • Custom providers: useValue, useClass, useFactory, useExisting
  • Injection tokens
  • Provider scopes
  • Circular dependencies
  • Lifecycle hooks
On this page

The problem

A service needs other objects: a database repository, a mailer, a clock. One way is to create them inside:

class SignupService {
  private users = new PostgresUserRepository();
  private mailer = new SendGridMailer(process.env.KEY);
}

Problems:

  • You cannot test it without a real database and real emails.
  • Changing the mailer means editing every class that creates one.
  • Every class creates its own copies, with their own connections.

Dependency injection

Dependency injection (DI) means a class receives its dependencies from outside (usually through its constructor) instead of creating them:

class SignupService {
  constructor(private users: UserRepository, private mailer: Mailer) {}
}

Now a test passes fakes (Lesson 206), and production passes real ones. The class depends on what it needs, not how to build it. This is the "D" in SOLID (Lesson 267).

Inversion of control (IoC): the framework, not your code, creates objects and connects them. Nest has an IoC container that:

  1. Reads each provider's constructor parameter types (TypeScript emits them as metadata).
  2. Creates the dependencies first, then the class.
  3. Keeps one shared instance of each provider (a singleton) by default and injects it wherever it is needed.

How Nest resolves dependencies

TypeScript
import { Injectable } from "@nestjs/common";

@Injectable()
export class Clock {
  now(): Date {
    return new Date();
  }
}

@Injectable()
export class GreetingService {
  constructor(private readonly clock: Clock) {}

  greeting(): string {
    const hour = this.clock.now().getHours();
    return hour < 12 ? "Good morning" : "Good afternoon";
  }
}

Register both in a module's providers, and Nest builds Clock first, then GreetingService with it. You never write new.

Behind the scenes, @Injectable() together with the TypeScript compiler options experimentalDecorators and emitDecoratorMetadata records that the constructor needs a Clock. That is why NestJS projects have these options on and import reflect-metadata. Note: interfaces and type aliases disappear when TypeScript compiles, so Nest cannot inject by an interface type. Use a class, or an injection token (below).

Custom providers

Writing providers: [Clock] is short for { provide: Clock, useClass: Clock }. You can choose differently:

FormUseExample
useValueA ready-made value or objectConfig objects, a fake in tests
useClassChoose a class (possibly a different one){ provide: Mailer, useClass: isProd ? SesMailer : ConsoleMailer }
useFactoryBuild it with a function, optionally with injected dependencies, can be asyncA database client that needs config and must connect first
useExistingAn alias for another providerTwo tokens pointing to the same instance

Injection tokens

To inject something that is not a class (a config object, an interface implementation), use a token: a string or, better, a Symbol or constant:

TypeScript
import { Inject, Injectable, Module } from "@nestjs/common";

export const PAYMENT_GATEWAY = Symbol("PAYMENT_GATEWAY");

export interface PaymentGateway {
  charge(amountPence: number, customerId: string): Promise<{ id: string }>;
}

export class FakePaymentGateway implements PaymentGateway {
  async charge(amountPence: number, customerId: string) {
    return { id: `fake_${customerId}_${amountPence}` };
  }
}

@Injectable()
export class CheckoutService {
  constructor(@Inject(PAYMENT_GATEWAY) private readonly payments: PaymentGateway) {}

  pay(customerId: string, amountPence: number) {
    return this.payments.charge(amountPence, customerId);
  }
}

@Module({
  providers: [
    CheckoutService,
    {
      provide: PAYMENT_GATEWAY,
      useFactory: () => (process.env.NODE_ENV === "production" ? new FakePaymentGateway() : new FakePaymentGateway())
    }
  ],
  exports: [CheckoutService]
})
export class CheckoutModule {}

(In a real app the production branch would return a Stripe gateway.) CheckoutService depends only on the PaymentGateway interface; the module decides which implementation is used. In a test, override the token with a fake (Lesson 211).

Provider scopes

ScopeInstancesUse
DEFAULT (singleton)One for the whole appAlmost everything. Fast. Must not store per-request data in fields
REQUESTA new instance per requestWhen you need request-specific state (for example the current tenant) injected deeply. Slower, and the scope "bubbles up" to everything that depends on it
TRANSIENTA new instance for every consumerEach class that injects it gets its own copy (for example a logger with a context name)

@Injectable({ scope: Scope.REQUEST }). Common interview trap: storing the current user in a field of a singleton service. All requests share that instance, so users would see each other's data. Pass request data as method arguments, or use request scope, or AsyncLocalStorage (the nestjs-cls library).

Circular dependencies

A needs B and B needs A: Nest cannot build either first. forwardRef(() => B) can work around it, but a circular dependency usually signals a design problem. Better: move the shared logic into a third service, or use events.

Lifecycle hooks

Nest calls methods at certain moments if your provider or module defines them:

HookWhen
onModuleInit()After the module's dependencies are resolved
onApplicationBootstrap()After all modules are initialised, before listening
onModuleDestroy()After a shutdown signal is received
beforeApplicationShutdown(signal)After all onModuleDestroy hooks; connections still open
onApplicationShutdown(signal)After connections are closed
TypeScript
import { Injectable, type OnApplicationShutdown, type OnModuleInit } from "@nestjs/common";

@Injectable()
export class DatabaseService implements OnModuleInit, OnApplicationShutdown {
  connected = false;

  async onModuleInit() {
    this.connected = true;
  }

  async onApplicationShutdown(signal?: string) {
    this.connected = false;
    console.log(`Database closed after ${signal ?? "shutdown"}`);
  }
}

Hooks may be async; Nest waits for them. Shutdown hooks run only if app.enableShutdownHooks() was called (or app.close() is called, as in tests). In NestJS 12, hooks run in order of the component hierarchy (dependencies before the things that depend on them), which changed from earlier versions; code that relied on the old order should be reviewed when upgrading.

How to say it in an interview

"Dependency injection means a class receives its dependencies, usually through the constructor, instead of creating them, which makes code testable and decoupled. Nest's IoC container reads constructor types from decorator metadata, builds dependencies first and shares a singleton of each provider by default. Since interfaces vanish at runtime I use injection tokens with Inject, and custom providers with useValue, useClass, useFactory or useExisting to choose implementations. Request and transient scopes exist, but I avoid storing request data on singletons. I treat circular dependencies as a design smell, and I use lifecycle hooks like onModuleInit and onApplicationShutdown with enableShutdownHooks for connecting and cleaning up."

Key words

WordMeaning
Dependency injectionGiving a class its dependencies from outside
Inversion of controlThe framework creates and connects objects
IoC containerThe part of Nest that builds and stores providers
Injection tokenA key (Symbol or string) identifying a provider
Custom provideruseValue, useClass, useFactory or useExisting
SingletonOne shared instance
Request scopeA new instance per request
Lifecycle hookA method Nest calls at a certain moment

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.