Skip to content

Instantly share code, notes, and snippets.

@jspdown
Created February 4, 2014 14:55
Show Gist options
  • Save jspdown/8805068 to your computer and use it in GitHub Desktop.
Save jspdown/8805068 to your computer and use it in GitHub Desktop.
simple dependency injection
class DInjector {
inject:any;
modules:any;
constructor() {
this.inject = {};
this.modules = {};
}
public register(name:string, dependency:string[], fn:any) {
this.inject[name] = {
dep: dependency,
fn: fn
};
}
private dependencyInjection(module:string) {
if (!this.modules.hasOwnProperty(module)) {
var self = this;
var args = [null];
this.inject[module].dep.forEach(function (itm) {
args.push(self.dependencyInjection(itm));
});
var cache = this.inject[module].fn.bind.apply(this.inject[module].fn, args);
this.modules[module] = new cache();
}
return (this.modules[module]);
}
public start() {
for (var name in this.inject) {
try { this.dependencyInjection(name) }
catch (err) { throw Error('injection loop with ' + name) }
}
}
}
var di = new DInjector();
class Router {
constructor(Bdd) {
console.log('ctor Router');
console.log('need to route on ', Bdd.host, ':', Bdd.port);
}
}
class Bdd {
host :string;
port :number;
constructor() {
console.log('ctor Bdd');
this.host = '127.0.0.1';
this.port = 4242;
}
}
di.register('Router', ['Bdd'], Router);
di.register('Bdd', [], Bdd);
di.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment