Custom providers cho phép kiểm soát cách NestJS tạo và inject dependencies:
useValue: inject giá trị cụ thể — thường dùng cho config objects, mocking trong tests:
{ provide: 'CONFIG', useValue: { apiKey: 'abc' } }useClass: chỉ định class khác để inject — dùng để swap implementation (mock, stub):
{ provide: UserService, useClass: MockUserService }useFactory: factory function tạo provider — hỗ trợ async và inject dependencies:
{ provide: 'DB', useFactory: async (config: ConfigService) => {
return createConnection(config.get('DB_URL'))
}, inject: [ConfigService] }useExisting: alias — inject cùng instance từ token khác:
{ provide: 'LOGGER', useExisting: WinstonLogger }Sử dụng string token cần @Inject('TOKEN') decorator trong constructor vì TypeScript không thể reflect string literals.
Custom providers control how NestJS creates and injects dependencies:
useValue: inject a specific value — for config objects or mocking in tests.
useClass: specify a different class — swap implementations (mock, stub).
useFactory: factory function creating provider — supports async and dependency injection:
{ provide: 'DB', useFactory: async (config) => createConn(config.get('URL')), inject: [ConfigService] }useExisting: alias — injects the same instance under a different token.
String tokens require @Inject('TOKEN') decorator because TypeScript cannot reflect string literals.