在 Aurelia 中注入多个使用 fetch HttpClient 的 类

Inject multiple classes that use the fetch HttpClient in Aurelia

我有一个名为 Infrastructure 的 class,我认为从 HttpClient 继承它会很方便。 class 公开了 get、post、put 和 delete 的方法。

import {Aurelia} from "aurelia-framework";
import {HttpClient, json} from "aurelia-fetch-client";

export default class Infrastructure extends HttpClient {
    get(url, queryString, contentType) {
        //..
    }

    post(url, data, contentType) {
        //..
    }

    put(url, data, contentType) {
        //..
    }

    delete(url, contentType) {
        //..
    }
}

我的想法是,我现在可以拥有注入 Infrastructure 的服务,它们可以在基础设施

上调用 configure
import {inject} from "aurelia-framework";
import Infrastructure from "./infrastructure";

@inject(Infrastructure)
export class InventoryService {
    constructor (infrastructure) {

        infrastructure.configure(config => {
            config
                .useStandardConfiguration()
                .withBaseUrl(`http://localhost:64441/inventory`);
        });

        this.infrastructure = infrastructure;
    }
}

我有几个使用 Infrastructure 的服务,一切正常。 问题是我不需要将 两个 这样的服务注入到同一个 class 上,并且配置的 baseUrl 会相互干扰。

在 Aurelia 中默认情况下一切都是单例,我明白这一点,但是在 Aurelia 中处理这种情况的首选方法是什么?

我知道我总是可以跳过配置 baseUrl,但是能够配置非常方便,我很好奇是否有更好的方法。

您可以使用不同的密钥注册同一个 "class" 的多个实例。注册码可以是任何东西,不需要是 class/constructor-function.

下面是一个例子。第一步是更改 Infrastructure class 以在构造函数中接受 baseUrl 参数:

export class Infrastructure {
  constructor(baseUrl) {
    this.configure(config => {
      config
        .useStandardConfiguration()
        .withBaseUrl(baseUrl);
      });
  }
  ...
}

接下来您需要使用不同的 Infrastructure 实例配置容器。下面的代码通常会在启动时发生,可能在 main.js:

// configure the container
container.registerInstance("Inventory", new Infrastructure("http://foo.com"));
container.registerInstance("Orders", new Infrastructure("http://bar.com"));

现在您将能够按键解决这些实例:

// resolve by name
var inventory = container.get("Inventory");
var orders = container.get("Orders");

或使用 @inject:

将它们声明为依赖项
import {inject} from "aurelia-framework";

@inject("Inventory", "Orders")
export class InventoryService {
  constructor (inventory, orders) {
    this.inventory = inventory;
    this.orders = orders;
  }
}

本期中有很多关于与您类似的场景的讨论: https://github.com/aurelia/dependency-injection/issues/73