Skip to content

Instantly share code, notes, and snippets.

@pimeo
Forked from jsmanifest/DIC.js
Last active April 8, 2020 11:18
Show Gist options
  • Save pimeo/6b18a9a492166724a44e6fe0fbb4c590 to your computer and use it in GitHub Desktop.
Save pimeo/6b18a9a492166724a44e6fe0fbb4c590 to your computer and use it in GitHub Desktop.
//
// Reference: https://medium.com/better-programming/dependency-injection-containers-in-javascript-5fd2c2b4be30
//
import parseFunction from 'parse-function'
const app = parseFunction({
ecmaVersion: 2017,
})
class DIC {
constructor() {
this.dependencies = {}
this.factories = {}
}
register(name, dependency) {
this.dependencies[name] = dependency
}
factory(name, factory) {
this.factories[name] = factory
}
get(name) {
if (!this.dependencies[name]) {
const factory = this.factories[name]
if (factory) {
this.dependencies[name] = this.inject(factory)
} else {
throw new Error('No module found for: ' + name)
}
}
return this.dependencies[name]
}
inject(factory) {
const fnArgs = app.parse(factory).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