DEFAULT | 每个提供者可以跨多个类共享。提供者生命周期严格绑定到应用程序生命周期。一旦应用程序启动,所有提供程序都已实例化。默认情况下使用单例范围。 |
REQUEST | 在请求处理完成后,将为每个传入请求和垃圾收集专门创建提供者的新实例 |
TRANSIENT | 临时提供者不能在提供者之间共享。每当其他提供者向 Nest 容器请求特定的临时提供者时,该容器将创建一个新的专用实例 |
提供者的默认值作用域是DEFAULT
TRANSIENT作用域
import { Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.TRANSIENT })
export class FactoryService {
getHello(): string {
return 'this is config';
}
}
import { Inject, Injectable } from '@nestjs/common';
import { FactoryService } from '../global/factory.service';
@Injectable()
export class ProService {
@Inject()
private readonly factoryService: FactoryService;
getHello(): FactoryService {
return this.factoryService;
}
}
import { ProService } from '../pro/pro.service';
@Injectable()
export class KeywordService {
constructor(
private readonly factoryService1: FactoryService,
private readonly proService: ProService,
) {}
findOne() {
const a = this.proService.getHello();
console.log(this.factoryService1 === a);
return this.factoryService1.getHello();
}
//console.log:false
把第一段代码的{ scope: Scope.TRANSIENT }删除
console.log:true
REQUEST范围
import { Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.REQUEST })
export class FactoryService {
private readonly id = Math.random();
constructor() {}
getHello(): number {
return this.id;
}
}
import {
Controller,
Get,
Inject,
Scope,
} from '@nestjs/common';
import { FactoryService } from '../global/factory.service';
@Controller({ path: 'keyword', scope: Scope.REQUEST })
export class KeywordController {
@Inject()
private readonly factoryService: FactoryService
@Get()
findOne() {
return this.factoryService.getHello();
}
上述代当每次请求时,id是会变化的,说明每次请求的实例不是同一个
如果去掉service和controller中的scope选项,则id是不变的,说明每次请求的实例是同一个
注:如果范围提供者,在控制器中使用,则表示该控制器也是范围的,即便没有scope选项