Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Experiment: Angular-Like Simple Dependency Injection
function Container(opt){
this.services = [];
if(opt)
{
this.owner = opt.owner || window;
}
}
Container.prototype = {
register: function(name, args){
if(Object.prototype.toString.call(args) == '[object Array]')
this.registerByArray(name, args);
else
this.registerByInfer(name, args);
},
registerByArray: function(name, args){
var registration = {
name: name,
func: args[args.length-1],
dependencies: args.splice(0,args.length-1)
};
this.services.push(registration);
},
registerByInfer: function(name, func){
var strFunc = func.toString();
var params =strFunc.substring(strFunc.indexOf('(')+1, strFunc.indexOf(')')).split(',');
var dependencies = [];
for(var i=0; i<params.length; i++){
var param = params[i].trim();
if(param == '')
continue;
dependencies.push(param);
}
this.services.push({
name: name,
func: func,
dependencies: dependencies
});
},
_getServiceByName: function(name){
var services = this.services;
for(var i=0; i<services.length; i++){
if(services[i].name == name)
return services[i];
}
return null;
},
resolve: function(name){
var registration = this._getServiceByName(name);
var deps = [];
for(var i=0; i<registration.dependencies.length; i++){
//this is not the best way
deps.push(this.resolve(registration.dependencies[i]));
}
return registration.func.apply(this.owner, deps);
}
};
//usage
var container =new Container();
container.register('dependency1', function(){
return function(){
console.log('my name is dependency 1');
}
});
container.register('dependency2', ['dependency1', function(dependency1){
return {
doSomething: function(){
dependency1();
console.log('do something');
}
}
}]);
container.register('testService', function(dependency1, dependency2){
return function(val){
dependency1();
dependency2.doSomething();
console.log(val);
};
});
container.resolve('testService')(12);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.