Skip to content

模块引用

Nest 提供了 ModuleRef 类,用于遍历内部的提供者列表,并通过注入令牌作为查找键来获取任意提供者的引用。ModuleRef 类还提供了一种动态实例化静态和作用域提供者的方式。ModuleRef 可以通过常规方式注入到类中:

typescript
@Injectable()
export class CatsService {
  constructor(private moduleRef: ModuleRef) {}
}

提示

ModuleRef 类从 @nestjs/core 包中导入。

获取实例

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

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

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

警告

不能使用 get() 方法获取作用域提供者(瞬态或请求作用域)。请使用下文描述的技术。了解如何控制作用域请参阅此处

要从全局上下文中获取提供者(例如,提供者已在其他模块中注入),可以将 { strict: false } 选项作为第二个参数传递给 get()

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

解析作用域提供者

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

typescript
@Injectable()
export class CatsService implements OnModuleInit {
  private transientService: TransientService;
  constructor(private moduleRef: ModuleRef) {}

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

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

typescript
@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
  }
}

要在多次 resolve() 调用中生成单个实例,并确保它们共享同一个生成的 DI 容器子树,可以向 resolve() 方法传递一个上下文标识符。使用 ContextIdFactory 类来生成上下文标识符。该类提供了一个 create() 方法,用于返回适当的唯一标识符。

typescript
@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
  }
}

提示

ContextIdFactory 类从 @nestjs/core 包中导入。

注册 REQUEST 提供者

手动生成的上下文标识符(通过 ContextIdFactory.create())代表的 DI 子树中,REQUEST 提供者为 undefined,因为它们不是由 Nest 依赖注入系统实例化和管理的。

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

typescript
const contextId = ContextIdFactory.create();
this.moduleRef.registerRequestByContextId(/* YOUR_REQUEST_OBJECT */, contextId);

获取当前子树

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

typescript
@Injectable()
export class CatsService {
  constructor(
    @Inject(REQUEST) private request: Record<string, unknown>,
  ) {}
}

提示

了解更多关于请求提供者的信息,请参阅此处

现在,使用 ContextIdFactory 类的 getByRequest() 方法基于请求对象创建上下文 ID,并将其传递给 resolve() 调用:

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

动态实例化自定义类

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

typescript
@Injectable()
export class CatsService implements OnModuleInit {
  private catsFactory: CatsFactory;
  constructor(private moduleRef: ModuleRef) {}

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

这种技术使你能够在框架容器之外有条件地实例化不同的类。

基于 NestJS 官方文档翻译