Created
November 1, 2018 03:52
-
-
Save SamanShafigh/8bd719d17e114243ea03e8256b3114e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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