Ser*_*eit 2 javascript dependency-injection ecmascript-6 aurelia aurelia-http-client
我有一个名为Infrastructure的类,我认为它可以很方便地继承HttpClient.这个类公开了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) {
//..
}
}
Run Code Online (Sandbox Code Playgroud)
我的想法是,我现在可以拥有注入的服务,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;
}
}
Run Code Online (Sandbox Code Playgroud)
我有几个使用Infrastructure这样的服务,一切正常.问题是我不需要将两个这样的服务注入到同一个类中,并且配置的相互baseUrl干扰.
Aurelia默认情况下一切都是单身人士,我理解这一点,但在Aurelia处理这种情况的首选方法是什么?
我知道我总是可以跳过配置baseUrl,但是配置起来非常方便,如果有更好的方法,我很好奇.
您可以使用不同的键注册同一"类"的多个实例.注册键可以是任何东西,它不需要是类/构造函数.
以下是一个例子.第一步是更改您的Infrastructure类以接受构造函数中的baseUrl参数:
export class Infrastructure {
constructor(baseUrl) {
this.configure(config => {
config
.useStandardConfiguration()
.withBaseUrl(baseUrl);
});
}
...
}
Run Code Online (Sandbox Code Playgroud)
接下来,您需要使用不同的Infrastructure实例配置容器.下面的代码通常会在启动时发生,可能在main.js:
// configure the container
container.registerInstance("Inventory", new Infrastructure("http://foo.com"));
container.registerInstance("Orders", new Infrastructure("http://bar.com"));
Run Code Online (Sandbox Code Playgroud)
现在,您将能够通过密钥解决这些实例:
// resolve by name
var inventory = container.get("Inventory");
var orders = container.get("Orders");
Run Code Online (Sandbox Code Playgroud)
或使用@inject以下方法将它们声明为依赖项:
import {inject} from "aurelia-framework";
@inject("Inventory", "Orders")
export class InventoryService {
constructor (inventory, orders) {
this.inventory = inventory;
this.orders = orders;
}
}
Run Code Online (Sandbox Code Playgroud)
在这个问题上有很多关于你的场景的讨论:https: //github.com/aurelia/dependency-injection/issues/73
| 归档时间: |
|
| 查看次数: |
1553 次 |
| 最近记录: |