您可以使用get 方法从容器中请求一个类型的实例:
class Foo {
}
let foo = container.get(Foo); // returns an instance of Foo.
在 TypeScript 中,您可能希望转换 get 方法的结果:
class Foo {
}
let foo = <Foo>container.get(Foo); // returns an instance of Foo.
如果您有多种类型实现了特定接口,请在应用启动时注册相应的实现:
// interface
class FooService {
getFoos(): Promise<Foo[]> {
throw new Error('not implemented');
}
}
class HttpFooService {
getFoos(): Promise<Foo[]> {
return fetch('https://api.evilcorp.com/foos')
.then(response => response.json());
}
}
class MockFooService {
getFoos(): Promise<Foo[]> {
return Promise.resolve([new Foo()]);
}
}
// app startup... configure the container...
if (TEST) {
container.registerHandler(FooService, c => c.get(MockFooService));
// or: container.registerInstance(FooService, new MockFooService());
} else {
container.registerHandler(FooService, c => c.get(HttpFooService));
// or: container.registerInstance(FooService, new HttpFooService());
}
// now when you @inject(Foo) or container.get(Foo) you'll get an instance of MockFooService or HttpFooService, depending on what you registered.
let foo = container.get(Foo); // returns an instance of MockFooService/HttpFooService.
我不确定这是否完全回答了您的问题。我从来没有使用过 Spring,也有一段时间没有做过任何 Java 编程。我没有完全遵循您问题中的代码。 Here's a link 到几个可能有用的容器/DI 用例。这是另一个可能有用的stackoverflow answer。这是 Aurelia DI docs。
附带说明,尽可能远离 container.get。使用它违反了依赖倒置原则。最好列出您的依赖项而不是主动检索它们:
好(ES6):
@inject(Foo, Bar)
class Baz {
constructor(foo, bar) {
}
}
好(打字稿):
@autoinject
class Baz {
constructor(foo: Foo, bar: Bar) {
}
}
不太好:
class Baz {
constructor() {
let foo = container.get(Foo);
let bar = container.get(Bar);
}
}