TExcelTAD
Home › Express & NestJS › Dependency Injection

Dependency Injection

Dependency injection (DI) means a class does not create the objects it needs — it receives them. In the Express Project Structure lesson you did this by hand: createBookmarkService({ repo }). Nest automates it with an IoC container (Inversion of Control): you declare what each class needs, and the container builds everything in the right order.

Without and with DI

ts
// Without DI: the class builds its own dependencies — hard to test, hard to swap
class OrdersService {
  private repo = new PostgresOrdersRepository(new Pool({ connectionString: '…' }));
}

// With DI: dependencies come in through the constructor
@Injectable()
class OrdersService {
  constructor(private readonly repo: OrdersRepository, private readonly mailer: MailService) {}
}

With DI, a test can pass a fake repository, production can pass the real one, and neither the service nor its callers change.

How Nest knows what to inject

TypeScript's emitDecoratorMetadata option makes the compiler record constructor parameter types as metadata. When Nest sees constructor(repo: OrdersRepository), it looks up the provider registered under the token OrdersRepository, creates it (recursively resolving its dependencies), caches it, and passes it in. By default every provider is a singleton: one instance shared by the whole app.

Building a tiny container

The best way to understand a DI container is to build one. This one has the same core behaviour as Nest's: tokens, recursive resolution, singletons, value/factory providers and cycle detection. Because standard TypeScript can't read constructor types at runtime without extra tooling, each class lists its dependencies in a static inject array — the same information Nest gets from metadata:

ts · try it yourself
type Token = string | (new (...args: any[]) => any);
type Provider =
  | { provide: Token; useClass: new (...args: any[]) => any }
  | { provide: Token; useValue: unknown }
  | { provide: Token; useFactory: (...deps: any[]) => unknown; inject?: Token[] };

const nameOf = (t: Token) => (typeof t === 'string' ? t : t.name);

class Container {
  private providers = new Map<Token, Provider>();
  private instances = new Map<Token, unknown>();
  private resolving: Token[] = [];

  register(p: Provider | (new (...args: any[]) => any)) {
    const provider: Provider = typeof p === 'function' ? { provide: p, useClass: p } : p;
    this.providers.set(provider.provide, provider);
    return this;
  }

  get<T>(token: Token): T {
    if (this.instances.has(token)) return this.instances.get(token) as T; // singleton cache
    const provider = this.providers.get(token);
    if (!provider) throw new Error(`No provider for ${nameOf(token)}`);
    if (this.resolving.includes(token)) {
      throw new Error(`Circular dependency: ${[...this.resolving, token].map(nameOf).join(' -> ')}`);
    }
    this.resolving.push(token);
    try {
      let instance: unknown;
      if ('useValue' in provider) instance = provider.useValue;
      else if ('useFactory' in provider) instance = provider.useFactory(...(provider.inject ?? []).map((t) => this.get(t)));
      else {
        const deps: Token[] = (provider.useClass as any).inject ?? [];
        instance = new provider.useClass(...deps.map((t) => this.get(t)));
      }
      this.instances.set(token, instance);
      return instance as T;
    } finally {
      this.resolving.pop();
    }
  }
}

// ---- application classes
class Logger {
  log(msg: string) { console.log(`[log] ${msg}`); }
}
class UsersRepository {
  static inject = ['DB_URL'];
  constructor(readonly url: string) {}
  find(id: number) { return { id, name: id === 1 ? 'Ana' : 'Bo' }; }
}
class UsersService {
  static inject = [UsersRepository, Logger];
  constructor(private repo: UsersRepository, private logger: Logger) {}
  getUser(id: number) {
    this.logger.log(`loading user ${id} from ${this.repo.url}`);
    return this.repo.find(id);
  }
}

const container = new Container()
  .register(Logger)
  .register(UsersRepository)
  .register(UsersService)
  .register({ provide: 'DB_URL', useValue: 'postgres://db/app' });

const users = container.get<UsersService>(UsersService);
console.log(users.getUser(1));
console.log('same instance?', users === container.get(UsersService));
console.log('logger shared?', container.get(Logger) === (users as any).logger);
[log] loading user 1 from postgres://db/app
{ id: 1, name: 'Ana' }
same instance? true
logger shared? true

Nobody called new UsersService(...). The container walked the graph UsersService → UsersRepository → 'DB_URL' and UsersService → Logger, built each piece once and wired them together.

Errors a container catches

The same container reports the two mistakes you'll meet in Nest: a missing provider and a circular dependency.

ts · try it yourself
class Container {
  private providers = new Map<Function, Function[]>();
  private resolving: Function[] = [];
  register(cls: Function, deps: Function[] = []) { this.providers.set(cls, deps); return this; }
  get(cls: Function): object {
    const deps = this.providers.get(cls);
    if (!deps) throw new Error(`Can't resolve ${cls.name}: no provider registered`);
    if (this.resolving.includes(cls)) {
      throw new Error(`Circular dependency: ${[...this.resolving, cls].map((c) => c.name).join(' -> ')}`);
    }
    this.resolving.push(cls);
    try {
      return Reflect.construct(cls, deps.map((d) => this.get(d)));
    } finally {
      this.resolving.pop();
    }
  }
}

class Mailer {}
class AuthService {}
class UsersService {}

try {
  new Container().register(AuthService, [Mailer]).get(AuthService);
} catch (e) { console.log((e as Error).message); }

try {
  new Container().register(AuthService, [UsersService]).register(UsersService, [AuthService]).get(AuthService);
} catch (e) { console.log((e as Error).message); }
Can't resolve Mailer: no provider registered
Circular dependency: AuthService -> UsersService -> AuthService

In Nest, the fix for the first is adding the provider (or importing the module that exports it). For a cycle, the best fix is usually to extract the shared logic into a third service; as a last resort Nest offers forwardRef(() => OtherService).

Provider recipes in Nest

The shorthand providers: [CatsService] means { provide: CatsService, useClass: CatsService }. The long forms let you swap implementations or inject non-class values:

ts
@Module({
  providers: [
    CatsService,                                                     // class shorthand
    { provide: 'API_URL', useValue: 'https://api.example.com' },     // a constant
    { provide: CatsRepository, useClass: InMemoryCatsRepository },   // swap the implementation
    {
      provide: 'DB_POOL',                                            // computed (sync or async)
      useFactory: async (config: ConfigService) => createPool(config.get('DATABASE_URL')),
      inject: [ConfigService],
    },
  ],
})
export class CatsModule {}

@Injectable()
export class CatsService {
  constructor(
    private readonly repo: CatsRepository,
    @Inject('API_URL') private readonly apiUrl: string,   // string tokens need @Inject()
  ) {}
}

Scopes

Scope Instance created Use
DEFAULT (singleton) once per app almost everything — stateless services
REQUEST once per incoming request per-request context (tenant, user) — slower, use sparingly
TRANSIENT once per consumer that injects it e.g. a logger with a per-class context
ts
@Injectable({ scope: Scope.REQUEST })
export class RequestContext { /* … */ }

Note: Because singletons are shared across all requests, never store per-request data (like "the current user") in a field of a default-scoped service.

Test yourself

By default, how many instances of an @Injectable() service does Nest create?

  1. One per request
  2. One per controller that uses it
  3. One for the whole application (singleton)
  4. A new one each time a method is called

How do you inject a value registered as { provide: 'API_URL', useValue: '…' }?

  1. constructor(apiUrl: API_URL)
  2. constructor(@Inject('API_URL') apiUrl: string)
  3. this.get('API_URL')
  4. It can't be injected

What is the main benefit of dependency injection for testing?

  1. Tests run faster on the CPU
  2. You can replace real dependencies with fakes without changing the class
  3. Tests don't need assertions
  4. It removes the need for modules