NestJS中文文档
基础 / 模块引用
已译 191/191

模块引用

Nest 提供 ModuleRef 类,用于在内部的提供者列表中导航,并以注入标记作为查找键,取得任意提供者的引用。ModuleRef 还可以动态实例化静态提供者和作用域提供者。像注入其他依赖一样把 ModuleRef 注入到类中即可:

cats.service.ts
@Injectable()
export class CatsService {
  constructor(private moduleRef: ModuleRef) {}
}
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }
}
提示

ModuleRef 类从 @nestjs/core 包导入。

获取实例

ModuleRef 实例(下文称为模块引用)有一个 get() 方法。默认情况下,该方法使用注入标记或类名,返回在当前模块中注册并实例化的提供者、控制器或可注入对象(例如守卫或拦截器)。如果找不到实例,则抛出异常。

cats.service.ts
@Injectable()
export class CatsService implements OnModuleInit {
  private service: Service;
  constructor(private moduleRef: ModuleRef) {}

  onModuleInit() {
    this.service = this.moduleRef.get(Service);
  }
}
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }

  onModuleInit() {
    this.service = this.moduleRef.get(Service);
  }
}
警告

无法用 get() 方法获取作用域提供者(瞬态或请求作用域,包括因依赖而隐式成为请求作用域的提供者)。请改用下文 解析作用域提供者 中介绍的技巧。想了解如何控制作用域,参见注入作用域一章。

要从全局上下文中获取提供者(例如该提供者注册在其他模块中),请把 { strict: false } 选项作为第二个参数传给 get()。

this.moduleRef.get(Service, { strict: false });

解析作用域提供者

要动态解析作用域提供者(瞬态或请求作用域),请使用 resolve() 方法,并把提供者的注入标记作为参数传入。

cats.service.ts
@Injectable()
export class CatsService implements OnModuleInit {
  private transientService: TransientService;
  constructor(private moduleRef: ModuleRef) {}

  async onModuleInit() {
    this.transientService = await this.moduleRef.resolve(TransientService);
  }
}
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }

  async onModuleInit() {
    this.transientService = await this.moduleRef.resolve(TransientService);
  }
}

resolve() 方法从该提供者自己的 DI 容器子树中返回一个唯一实例。每棵子树都有唯一的上下文标识符,因此如果你多次调用该方法并比较实例引用,会发现它们并不相等。

cats.service.ts
@Injectable()
export class CatsService implements OnModuleInit {
  constructor(private moduleRef: ModuleRef) {}

  async onModuleInit() {
    const transientServices = await Promise.all([
      this.moduleRef.resolve(TransientService),
      this.moduleRef.resolve(TransientService),
    ]);
    console.log(transientServices[0] === transientServices[1]); // false
  }
}
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }

  async onModuleInit() {
    const transientServices = await Promise.all([
      this.moduleRef.resolve(TransientService),
      this.moduleRef.resolve(TransientService),
    ]);
    console.log(transientServices[0] === transientServices[1]); // false
  }
}

要在多次 resolve() 调用之间得到同一个实例,并确保它们共享同一个生成的 DI 容器子树,请给 resolve() 方法传入一个上下文标识符。使用 ContextIdFactory 类生成上下文标识符:它的 create() 方法返回一个新的唯一标识符。

cats.service.ts
@Injectable()
export class CatsService implements OnModuleInit {
  constructor(private moduleRef: ModuleRef) {}

  async onModuleInit() {
    const contextId = ContextIdFactory.create();
    const transientServices = await Promise.all([
      this.moduleRef.resolve(TransientService, contextId),
      this.moduleRef.resolve(TransientService, contextId),
    ]);
    console.log(transientServices[0] === transientServices[1]); // true
  }
}
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }

  async onModuleInit() {
    const contextId = ContextIdFactory.create();
    const transientServices = await Promise.all([
      this.moduleRef.resolve(TransientService, contextId),
      this.moduleRef.resolve(TransientService, contextId),
    ]);
    console.log(transientServices[0] === transientServices[1]); // true
  }
}
提示

ContextIdFactory 类从 @nestjs/core 包导入。

注册 REQUEST 提供者

手动生成的上下文标识符(由 ContextIdFactory.create() 创建)所代表的 DI 子树中,REQUEST 提供者是 undefined,因为这些子树并非由 Nest 依赖注入系统实例化和管理。

要为手动创建的 DI 子树注册自定义的 REQUEST 对象,请使用 ModuleRef#registerRequestByContextId() 方法:

const contextId = ContextIdFactory.create();
this.moduleRef.registerRequestByContextId(/* 你的请求对象 */, contextId);

获取当前子树

有时你可能想在请求上下文中解析某个请求作用域提供者的实例。假设 CatsService 是请求作用域的,而你想解析同样是请求作用域提供者的 CatsRepository 实例。要共享同一个 DI 容器子树,你必须取得当前的上下文标识符,而不是生成一个新的(例如上文所示的 ContextIdFactory.create() 函数)。要取得当前上下文标识符,先通过 @Inject() 装饰器注入请求对象:

cats.service.ts
@Injectable()
export class CatsService {
  constructor(
    @Inject(REQUEST) private request: Record<string, unknown>,
  ) {}
}
@Injectable()
@Dependencies(REQUEST)
export class CatsService {
  constructor(request) {
    this.request = request;
  }
}
提示

关于请求提供者的更多内容,参见注入作用域一章中的请求提供者小节。

接着使用 ContextIdFactory 类的 getByRequest() 方法取得与该请求对象关联的上下文标识符,并把它传给 resolve() 调用:

const contextId = ContextIdFactory.getByRequest(this.request);
const catsRepository = await this.moduleRef.resolve(CatsRepository, contextId);

动态实例化自定义类

要动态实例化一个此前未注册为提供者的类,请使用模块引用的 create() 方法:

cats.service.ts
@Injectable()
export class CatsService implements OnModuleInit {
  private catsFactory: CatsFactory;
  constructor(private moduleRef: ModuleRef) {}

  async onModuleInit() {
    this.catsFactory = await this.moduleRef.create(CatsFactory);
  }
}
@Injectable()
@Dependencies(ModuleRef)
export class CatsService {
  constructor(moduleRef) {
    this.moduleRef = moduleRef;
  }

  async onModuleInit() {
    this.catsFactory = await this.moduleRef.create(CatsFactory);
  }
}

这种技巧让你可以在框架容器之外按条件实例化不同的类。