Skip to content

Instantly share code, notes, and snippets.

@xMartin
Last active August 29, 2015 14:05
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 xMartin/9f3e5e46e8527e0182af to your computer and use it in GitHub Desktop.
Save xMartin/9f3e5e46e8527e0182af to your computer and use it in GitHub Desktop.
JS DIContainer
function DIContainer(constructors) {
this._instances = {};
this._constructors = {};
for (var id in constructors) {
this.set(id, constructors[id]);
}
}
DIContainer.prototype.get = function (id) {
var entry = this._instances[id];
if (entry) {
return entry;
}
return this._instances[id] = this._constructors[id].call(this, this);
};
DIContainer.prototype.set = function (id, constructor) {
this._constructors[id] = constructor;
};
////
var Dep1 = require('dep1');
var Dep2 = require('dep2');
var container = new DIContainer({
myService: function () {
return new Dep1();
},
myObject: function () {
return new Dep2(this.get('myService'));
}
});
////
var Dep3 = require('dep3');
container.set('anotherThing', function (container) {
return new Dep3(containger.get('myService'));
});
////
var myObject = container.get('myObject');
var anotherThing = container.get('anotherThing');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment