3

I want to create a factory that is able to create a new instance of a class (MyClass, implementing an abstract class) that is using dependency injection.

I would like the factory to look like this:

Factory

export class Factory {

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

}

However, the EventAggregator is not injected into MyClass when I take this approach.

How can I do this?

Interface

export abstract class MyClassInterface {

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

}

Class

@inject(EventAggregator)
export class MyClass {

  constructor(EventAggregator) {}

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

}

Thanks in advance!

4

1 回答 1

4

第一个选项

使用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();
  }
}
于 2017-07-20T16:23:35.453 回答