Skip to content

Instantly share code, notes, and snippets.

@jsmanifest
Created April 7, 2020 15:28
Show Gist options
  • Save jsmanifest/6fe35e60d7f0c1d3af70868cd90f8be3 to your computer and use it in GitHub Desktop.
Save jsmanifest/6fe35e60d7f0c1d3af70868cd90f8be3 to your computer and use it in GitHub Desktop.
class DIC {
constructor() {
this.dependencies = {}
this.factories = {}
}
register(name, dependency) {
this.dependencies[name] = dependency
}
factory(name, factory) {
this.factories[name] = factory
}
get(name, args) {
if (!this.dependencies[name]) {
const factory = this.factories[name]
if (factory) {
this.dependencies[name] = this.inject(factory, args)
} else {
throw new Error('No module found for: ' + name)
}
}
return this.dependencies[name]
}
inject(factory, args = []) {
const fnArgs = args.map((arg) => this.get(arg))
return new factory(...fnArgs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment