Trung BìnhNestJS iconNestJS

Custom providers: useValue, useClass, useFactory, useExisting — khi nào dùng cái nào?

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:

typescript
{ provide: 'CONFIG', useValue: { apiKey: 'abc' } }

useClass: chỉ định class khác để inject — dùng để swap implementation (mock, stub):

typescript
{ provide: UserService, useClass: MockUserService }

useFactory: factory function tạo provider — hỗ trợ async và inject dependencies:

typescript
{ provide: 'DB', useFactory: async (config: ConfigService) => {
  return createConnection(config.get('DB_URL'))
}, inject: [ConfigService] }

useExisting: alias — inject cùng instance từ token khác:

typescript
{ provide: 'LOGGER', useExisting: WinstonLogger }

Sử dụng string token cần @Inject('TOKEN') decorator trong constructor vì TypeScript không thể reflect string literals.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS