2.0 注入作用域

DEFAULT

每个提供者可以跨多个类共享。提供者生命周期严格绑定到应用程序生命周期。一旦应用程序启动,所有提供程序都已实例化。默认情况下使用单例范围。

REQUEST

在请求处理完成后,将为每个传入请求和垃圾收集专门创建提供者的新实例

TRANSIENT

临时提供者不能在提供者之间共享。每当其他提供者向 Nest 容器请求特定的临时提供者时,该容器将创建一个新的专用实例

  1. 提供者的默认值作用域是DEFAULT

  1. 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

  1. 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选项

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值