Create a new instance of a class that is using dependency injection in Aurelia

余生长醉 提交于 2019-12-07 14:45:26

问题


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


来源:https://stackoverflow.com/questions/45219953/create-a-new-instance-of-a-class-that-is-using-dependency-injection-in-aurelia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!