ModuleRef
Resolves providers dynamically from the DI container at runtime.
Syntax
moduleRef.get(token, options?) | moduleRef.resolve(token) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
token | Type | string | symbol | No | The provider token to look up. |
options | object | No | Options such as { strict: false } to search the whole app. |
Returns
any — The resolved provider instance (or a Promise for resolve()).
Examples
import { Injectable, OnModuleInit } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { CatsService } from './cats.service';
@Injectable()
export class AppService implements OnModuleInit {
private cats: CatsService;
constructor(private moduleRef: ModuleRef) {}
onModuleInit() {
this.cats = this.moduleRef.get(CatsService, { strict: false });
}
}
Notes
get() retrieves singleton instances; resolve() returns a Promise and is
required for request- or transient-scoped providers. Use ModuleRef for
dynamic resolution, not as a substitute for constructor injection.