配置作用域

配置作用域

在 injection 体系中,有三种作用域。

  • Singleton 单例,全局唯一(进程级别)
  • Request 默认 ,请求作用域,生命周期随着请求链路,在请求链路上唯一,请求结束立即销毁
  • Prototype 原型作用域,每次调用都会重复创建一个新的对象

在这三种作用域中,midway 的默认作用域为 请求作用域 ,这也意味着,如果我们需要将一个对象定义为其他两种作用域,需要额外的配置。

injection 提供了 @scope 装饰器来定义一个类的作用域。

@scope(ScopeEnum.Prototype)
@provide('petrol')
export class PetrolEngine implements Engine {
  capacity = 10;
}

@scope(ScopeEnum.Singleton)
@provide('diesel')
export class DieselEngine implements Engine {
  capacity = 20;
}

// in IoC Container
assert(container.getAsync('petrol') === container.getAsync('petrol'))  // false
assert(container.getAsync('diesel') === container.getAsync('diesel'))  // true

插件,在 midway 中为单例,不可配置。