Kind: Interface
Source: packages/common/interfaces/modules/provider.interface.ts
Part of: Common
Interface defining a Class type provider.
For example:
typescriptconst configServiceProvider = {
provide: ConfigService,
useClass:
process.env.NODE_ENV === 'development'
? DevelopmentConfigService
: ProductionConfigService,
};
ClassProvider defines a dependency injection provider that creates a token’s value by instantiating a class. It maps an InjectionToken to a concrete implementation type and can optionally configure the provider scope and durability behavior.
Properties
| Property | Type |
|---|---|
provide | InjectionToken |
useClass | Type<T> |
scope | Scope |
inject | never |
durable | boolean |
Diagram
mermaidgraph LR A[InjectionToken<br/>provide] --> B[ClassProvider] B --> C[Implementation Class<br/>useClass] C --> D[DI Container] D --> E[Injected Consumer] B --> F[Scope<br/>scope] B --> G[Durability<br/>durable]
Usage
typescriptimport { Scope } from '@nestjs/common';
import type { ClassProvider } from '@nestjs/common';
class DevelopmentConfigService {
getDatabaseUrl() {
return 'postgres://localhost/dev';
}
}
class ProductionConfigService {
getDatabaseUrl() {
return process.env.DATABASE_URL;
}
}
const configServiceProvider: ClassProvider = {
provide: 'CONFIG_SERVICE',
useClass:
process.env.NODE_ENV === 'development'
? DevelopmentConfigService
: ProductionConfigService,
scope: Scope.DEFAULT,
durable: true,
};
// Register in a module:
// @Module({
// providers: [configServiceProvider],
// exports: ['CONFIG_SERVICE'],
// })
AI Coding Instructions
- Use
provideto define the token consumers inject, anduseClassto define the concrete class instantiated for that token. - Choose
useClasswhen the dependency should be created by the container rather than supplied as an existing value. - Ensure the class assigned to
useClassis constructible and that its own constructor dependencies are registered providers. - Configure
scopeonly when lifecycle behavior differs from the default singleton scope. - Do not add an
injectarray to aClassProvider; constructor dependencies are resolved from theuseClasstype automatically.
Used by
3 references from 3 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.
Imported by (3)
isClassProvider—packages/core/injector/helpers/provider-classifier.ts:9Module—packages/core/injector/module.ts:44DependenciesScanner—packages/core/scanner.ts:75
Was this page helpful?