[英]Inject multiple classes that use the fetch HttpClient in Aurelia
我有一个称为Infrastructure的类,我认为从HttpClient
继承该类很方便。 此类公开获取,发布,放置和删除的方法。
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
的服务,并且一切正常。 问题是我不需要将两个这样的服务注入到同一类中,并且配置的baseUrl
会相互干扰。
我知道,在Aurelia中,默认情况下一切都是单例,但是在Aurelia中处理这种情况的首选方式是什么?
我知道我总是可以跳过配置baseUrl
,但是能够进行配置非常方便,我很好奇是否有更好的方法。
您可以使用不同的键来注册同一“类”的多个实例。 注册键可以是任何东西,而不必是类/构造函数。
下面是一个例子。 第一步是将Infrastructure
类更改为在构造函数中接受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
它们声明为依赖@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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.