Providers, modules, and dependency injection

12.6.0

Put reusable behavior in a provider. A module registers the providers and controllers that belong to a feature.

On this page

Inject a service into a controller

Mark the service with Injectable and register it under providers. A controller can ask for that service in its constructor. Nest resolves the dependency when it creates the controller.

import { Controller, Get, Injectable, Module } from "@nestjs/common";

@Injectable()
class CatalogService {
  list() {
    return ["Pen", "Notebook"];
  }
}

@Controller("catalog")
class CatalogController {
  constructor(private readonly catalog: CatalogService) {}

  @Get()
  list() {
    return this.catalog.list();
  }
}

@Module({ controllers: [CatalogController], providers: [CatalogService] })
export class CatalogModule {}

Share providers between modules

By default, a provider belongs to its module. Export a provider from its module and import that module where the provider is needed. Register a feature module in the root module’s imports to include it in the app.

import { Module } from "@nestjs/common";
import { CatalogService } from "./catalog.service";
import { OrdersController } from "./orders.controller";

@Module({ providers: [CatalogService], exports: [CatalogService] })
class CatalogModule {}

@Module({ imports: [CatalogModule], controllers: [OrdersController] })
class OrdersModule {}

@Module({ imports: [OrdersModule] })
export class AppModule {}

Official references