In Aurelia, I have several classes which depend on the same configuration. Using IoC/DI, it seems natural that this config can be supplied as a constructor parameter. For example:
@autoinject
export class CustomerService {
constructor(config: IRemoteServiceConfig) {
}
}
@autoinject
export class GummyBearService {
constructor(config: IRemoteServiceConfig) {
}
}
In the simplest example, the IRemoteServiceConfig might look something like this (removed other stuff for brevity):
export IRemoteServiceConfig {
endpoint: string;
apiKey?: string;
// etc. several other settings
}
Having the configuration injected in constructor is ideal for testing and doesn't require me to read configs and settings in each class.
The services depend on the same configuration, which I want to define once - during startup - in my application.
Reading through the Aurelia docs on dependency injection, I see several methods are available for this purpose, such as registerInstance()
, registerResolver()
and registerSingleton()
. The docs do lack some context on how and where to define this.
I've started out with something like the following in the configure()
section of my startup routine:
// register a static config; for brevity these are hardcoded settings
// but could come from anywhere
container.registerSingleton(IRemoteServiceConfig, () => {
return <IRemoteServiceConfig> {
endpoint: 'http://foo.com/api/v23/',
apiKey: 'abc'
}
});
It just doesn't seem to pick anything up (no errors). But this may also be just my ignorance on how to initialise the container.
My question: how and where can I define the IRemoteServiceConfig in Aurelia, if at all, so that once the DI kicks in for the services it automatically picks up my (hardcoded) config?
Note that in this SO question it is mentioned that "it can’t work with interfaces because TypeScript compiles those away at runtime.". The question is also +2 years old and both in Aurelia as well as in TypeScript a lot has changed. Regardless if this is still the case, the same question applies for an instance of a class rather than an interface as well.
Also please note that I'm aware of libs such as aurelia-configuration, which seem suited to store appsettings in a config file (and which work just fine). This would make more sense for the example given. But the question is purely related to how can I define an interface or specific instance of a class to be resolved by the Aurelia DI.