Module Reference is a NestJS API that provides dynamic access to providers and modules outside the standard Dependency Injection container, enabling Manual Provider Instantiation.
Usage
Inject ModuleRef to access providers dynamically:
import { ModuleRef } from '@nestjs/core';
@Injectable()
export class CatsService {
constructor(private moduleRef: ModuleRef) {}
async getCircularDependency() {
// Resolve circular dependency dynamically
const dogsService = await this.moduleRef.get(DogsService);
return dogsService.findAll();
}
async getRequestScopedService() {
// Must use STRICT scope for request-scoped providers
const service = await this.moduleRef.resolve(RequestScopedService,
contextId
);
}
}Key methods
get(): Retrieve a singleton provider synchronouslyresolve(): Retrieve a provider asynchronously (supports request-scoped)create(): Create a new instance of a provider
Use cases
- Breaking circular dependencies
- Dynamic provider selection based on runtime conditions
- Accessing request-scoped providers outside request context
- Testing scenarios requiring manual provider resolution