我想创建一个能够创建使用依赖注入的类的新实例(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) {}
}
提前致谢!
答案 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();
}
}