Skip to content

Instantly share code, notes, and snippets.

@SamanShafigh
Created November 1, 2018 03:52
Show Gist options
  • Save SamanShafigh/8bd719d17e114243ea03e8256b3114e3 to your computer and use it in GitHub Desktop.
Save SamanShafigh/8bd719d17e114243ea03e8256b3114e3 to your computer and use it in GitHub Desktop.
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