构造器注入

构造器注入

除了标准的属性注入方法之外,midway 在一定程度上支持了构造器注入的方式,来让一些应用或者三方包平稳过度。

同样还是使用 @inject 装饰器。

@provide()
export class A {
  config = {
    c: 20
  };
}

@provide()
export class B {
  config = {
    c: 40
  };
}

@provide()
export class BaseService {

  config;
  plugin2;

  constructor(
    @inject() a,
    @config('hello') config,
    @inject() b,
    @plugin('plugin2') plugin2
  ) {
    this.config = Object.assign(config, {
      c: a.config.c + b.config.c + config.c
    });
    this.plugin2 = plugin2;
  }

}

在一个类的构造器中,我们可以还可以使用其他的类似 @config, @plugin, @logger 等装饰器。只要是通过 IoC 管理的对象,都能够被自动依赖和注入。