Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
export default class Container {
constructor(builder) {
this.services = new Map();
if (builder !== undefined) {
Object.keys(builder).forEach(name => this.register(name, builder[name]));
}
}
/**
* Register a service
*
* @param name
* @param sig service signature
*/
register(name, sig) {
this.services.set(name, {sig, instance: null})
}
/**
* Get a service
*
* @param name
*/
get(name): any {
const service = this.services.get(name)
if (service.instance !== null) {
return service.instance;
}
const instance = service.sig.constructor(this);
this.services.set(name, {sig: service.sig, instance})
return instance;
}
/**
* Boot those services that need to be booted
*/
public boot() {
const bootP = [];
this.services.forEach((service, name) => {
const sig = service.sig;
if (sig.tags !== undefined && sig.tags.includes('boot')) {
bootP.push(this.get(name).boot(this));
}
})
return bootP;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment