Master @Injectable(), useClass/useValue/useFactory providers, module vs global scope, and resolving circular dependencies with forwardRef
0 / 5 completed
1 / 5
What does the @Injectable() decorator do in NestJS?
@Injectable(): registers the class with NestJS's inversion-of-control container. Any class decorated with @Injectable() can be listed in a module's providers array and injected into controllers or other services via constructor injection: constructor(private readonly userService: UserService) {}.
2 / 5
What is the difference between useClass and useValue in a NestJS provider definition?
Provider tokens:{ provide: APP_CONFIG, useClass: ConfigService } — NestJS instantiates ConfigService. { provide: APP_CONFIG, useValue: { apiUrl: 'https://...' } } — the object is used as-is. useFactory is a third option: a function (possibly async) that returns the provider value, enabling dynamic initialisation.
3 / 5
What does useFactory enable in NestJS provider configuration?
useFactory: Example: { provide: DATABASE, useFactory: async (config: ConfigService) => createConnection(config.dbUrl), inject: [ConfigService] }. NestJS calls the factory, injecting the listed tokens. Async factories are awaited before the app bootstraps, making them ideal for database connections and external config fetching.
4 / 5
What is module scope vs global scope for NestJS providers?
Module vs global scope: By default, a provider is only injectable within the module that declares it. To share it, either export it and import the module elsewhere, or decorate the module with @Global(). Global modules register their exports in the root container, making providers like ConfigService or LoggerService universally available without repeated imports.
5 / 5
How does NestJS handle circular dependencies between providers?
forwardRef: When ServiceA depends on ServiceB and vice versa, TypeScript's class declarations haven't loaded one when the other is processed. forwardRef(() => ServiceB) wraps the reference in a thunk resolved lazily. NestJS also accepts { provide: ServiceB, useExisting: forwardRef(() => ServiceB) }. Circular deps are a code smell — the better fix is extracting shared logic to a third provider.