You can request an instance of a type from the container using the get
method:
class Foo {
}
let foo = container.get(Foo); // returns an instance of Foo.
In TypeScript, you'd probably want to cast the result of the get
method:
class Foo {
}
let foo = <Foo>container.get(Foo); // returns an instance of Foo.
If you have multiple types that implement a particular interface, register the appropriate implementation at app startup:
// 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.
I'm not sure if this answers your question entirely. I've never used Spring and haven't done any Java programming in a while. I didn't quite follow the code in your question. Here's a link to several container/DI use cases that might be helpful. Here's another stackoverflow answer that might be helpful. Here are the Aurelia DI docs.
As a side note, stay away from container.get when possible. Using it violates the dependency inversion principle. Better to list your dependencies than to actively retrieve them:
Good (ES6):
@inject(Foo, Bar)
class Baz {
constructor(foo, bar) {
}
}
Good (TypeScript):
@autoinject
class Baz {
constructor(foo: Foo, bar: Bar) {
}
}
Not so good:
class Baz {
constructor() {
let foo = container.get(Foo);
let bar = container.get(Bar);
}
}