Skip to content

Instantly share code, notes, and snippets.

@dadamssg
Last active June 13, 2017 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dadamssg/ac5639eb222e81dbf13afe652b8476e5 to your computer and use it in GitHub Desktop.
Save dadamssg/ac5639eb222e81dbf13afe652b8476e5 to your computer and use it in GitHub Desktop.
class Container {
constructor () {
this._definitions = {}
}
register (id, func, factory = false) {
if (typeof func !== 'function') {
throw new Error('Invalid service function.')
}
this._definitions[id] = {
func,
factory
}
}
prime (id, instance) {
this._definitions[id] = {instance}
}
get (id) {
const definition = this._definitions[id]
if (!definition) {
throw new Error(`No service definition: ${id}`)
}
if (definition.factory) {
return definition.func(this)
}
if (!definition.instance) {
definition.instance = definition.func(this)
}
return definition.instance
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment