Providers
Providers are classes Nest can inject as dependencies, most commonly services.
@Injectable()A provider is any class that Nest can create and inject into other classes. Services, repositories, factories, and helpers are all providers.
The core idea
Instead of a class creating its own dependencies with new, it declares what it needs and Nest supplies ready-made instances. This is dependency injection, and providers are the things that get injected.
A class becomes an injectable provider when you mark it with @Injectable() and list it in a module's providers array.
Example
import { Injectable } from '@nestjs/common';
@Injectable()
export class LoggerService {
log(message: string) {
console.log(`[LOG] ${message}`);
}
}When to use it
- A developer creates an EmailService provider so controllers can send emails without knowing which email library is used underneath.
- A team registers a database repository as a provider so it can be injected into multiple services across different modules.
- An architect defines a LoggerService provider and exports it from a shared module so any feature module can inject it without re-declaring it.
More examples
Simple service provider
Shows the minimal @Injectable service — the most common type of provider in a NestJS app.
import { Injectable } from '@nestjs/common';
@Injectable()
export class CatsService {
private cats: string[] = [];
findAll(): string[] {
return this.cats;
}
}Register provider in module
Demonstrates that providers must be listed in the providers array of a module before they can be injected.
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
@Module({
controllers: [CatsController],
providers: [CatsService], // registered here
})
export class CatsModule {}Provider with multiple dependents
Illustrates how a single provider (LoggerService) can be injected into multiple unrelated services by the DI container.
// LoggerService injected into two different services
@Injectable()
export class LoggerService {
log(msg: string) { console.log(msg); }
}
@Injectable()
export class UsersService {
constructor(private logger: LoggerService) {}
findAll() { this.logger.log('findAll called'); return []; }
}
@Injectable()
export class OrdersService {
constructor(private logger: LoggerService) {}
create() { this.logger.log('order created'); }
}
Discussion