在Aurelia中创建使用依赖项注入的类的新实例

时间:2017-07-20 16:05:26

标签: dependency-injection aurelia aurelia-framework aurelia-di

我想创建一个能够创建使用依赖注入的类的新实例(MyClass,实现抽象类)的工厂。

我希望工厂看起来像这样:

export class Factory {

  public static makeMyClass() {
    return new MyClass();
  }

}

但是,当我采用这种方法时,EventAggregator不会注入MyClass。

我该怎么做?

接口

export abstract class MyClassInterface {

  abstract connect();
  abstract disconnect();
  abstract send(message: string);

}

@inject(EventAggregator)
export class MyClass {

  constructor(EventAggregator) {}

  connect() {}
  disconnect() {}
  send(message: string) {}

}

提前致谢!

1 个答案:

答案 0 :(得分:3)

第一个选项

使用NewInstance.of解析器:

import {inject, NewInstance} from 'aurelia-framework';

@inject(NewInstance.of(MyClass))
export class MyViewModel {
   constructor(myClass) {
     this.myClass = myClass; //myClass is always a new instance
   }
}

第二个选项

使用工厂:

import {inject, EventAggregator} from 'aurelia-framework';

@inject(EventAggregator)
export class MyFactory {

  constructor(eventAggregator) {
    this.eventAggregator = eventAggregator;
  }

  public static createMyClass() {
    return new MyClass(this.eventAggregator);
  }
}

@inject(MyFactory)
export class MyViewModel {

  constructor(myFactory) {
    this.myClass = myFactory.createMyClass();
  }
}