Create a new instance of a class that is using dep

2019-05-27 15:03发布

问题:

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!

回答1:

First Option

Use the NewInstance.of resolver:

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

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

Second Option

Use a factory:

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();
  }
}