← Blog

Dependency Injection in NestJS: The Basics

A controller should focus on handling requests, not on constructing services, database clients, or other objects. Dependency Injection (DI) solves this by allowing a class to declare what it needs and letting NestJS provide those dependencies.

Without dependency injection

A controller that creates its own service is tightly connected to that implementation:

export class CatsController {
  private catsService = new CatsService();
}

Replacing CatsService for a test or a different implementation now requires changing the controller.

Let Nest inject the service

First, mark the service as injectable:

import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  findAll() {
    return ['Milo', 'Luna'];
  }
}

Then declare it in the module and request it through the controller constructor:

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  findAll() {
    return this.catsService.findAll();
  }
}

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

Nest reads the constructor dependency metadata, finds the registered provider, and supplies its instance. You do not need to instantiate the service yourself.

Why constructor injection?

Constructor injection makes dependencies visible as soon as you read a class. It also makes testing straightforward: configure the testing module with a substitute provider and test the controller without relying on the real service.

One important detail: TypeScript interfaces disappear at runtime. Nest cannot use an interface alone as an injection token. For non-class dependencies, register a token and use @Inject().

In short: DI means asking for a dependency rather than building it yourself. It keeps classes focused and makes implementations easier to replace.

Reference: NestJS Providers