Last active
August 29, 2015 14:05
-
-
Save xMartin/9f3e5e46e8527e0182af to your computer and use it in GitHub Desktop.
JS DIContainer
This file contains hidden or 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
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