实例化对象时的 Aurelia 依赖注入

Aurelia dependency injection when instantiating objects

如果我创建一个支持 class,例如已将 HttpClient 注入其中的 UserList,那么实例化 class 的任何人都必须在构造函数中将 HttpClient 对象传递给它。 @inject(HttpClient) 不应该负责获取 HttpClient 单例并将其注入构造函数吗?否则,每个需要引用 UserList 的 class 也将获得对 HttpClient 的引用,以便它可以将其传递给 UserList 构造函数(并破坏注入的目的)。

UserList.ts

@inject(HttpClient)
export class UserList {
    constructor(public http: HttpClient){
    }
...
}

DoSomething.ts

export class DoSomething {
    userList: UserList;

    constructor(){
         this.userList = new UserList(); //doesn't work without passing HttpClient
    }
}

为了完成这项工作,我必须在 DoSomething class 中获取对 HttpClient 的引用,即使它不会直接使用它。似乎实现不佳的工作版本:

DoSomething.ts

@inject(HttpClient)
export class DoSomething {
    userList: UserList;

    constructor(public http: HttpClient){
         this.userList = new UserList(http); 
    }
}

如果您想使用 Aurelia dependency injection,您需要导入所需的模块:

import {HttpClient} from 'aurelia-fetch-client';
import {inject} from 'aurelia-framework';

@inject(HttpClient)
export class DoSomething{

    constructor(http){
        // do your stuff
    }

}

这是 ES6 实现,我使用的是这个,但我相信您需要更改的只是 constructor 中的 type

您需要在 DoSomething 中注入 UserList

import {UserList} from 'where-ever-user-list-is';
import {inject} from 'aurelia-framework';

@inject(UserList)
export class DoSomething {
    userList: UserList;

    constructor(userList){
         this.userList = userList
    }
}

如果你使用打字稿,不用担心这个。 使用@autoinject 看看奇迹发生!

像这样:

import {autoinject} from 'aurelia-framework';

@autoinject()
export class UserList {
    constructor(private http: HttpClient){
    }
...
}

在其他文件中:

import {autoinject} from 'aurelia-framework';

@autoinject()
export class DoSomething {
    constructor(private userList: UserList){
    }
}

TypeScript 编译器将发出类型元数据,Aurelia 将以正确的方式读取此注入实例!

更多信息:http://aurelia.io/docs.html#/aurelia/dependency-injection/1.0.0-beta.1.2.3/doc/article/dependency-injection-basics

处理此问题的正确方法是使用 Factory 解析器

import { Factory } from 'aurelia-framework';

@inject(Factory.of(UserList))
export class DoSomething {

    userList: UserList;

    constructor(UserList) {

        // this is a factory, so you call the function without new
        this.userList = UserList();
    }
}

@inject(HttpClient)
export class UserList {

    http: HttpClient;

    constructor(HttpClient) {
        this.http = HttpClient;
    }
}

有关详细信息,请参阅此 related question, or the official docs 中给出的答案。