Skip to content

Instantly share code, notes, and snippets.

@ova2
Created September 11, 2018 19:58
Show Gist options
  • Save ova2/4cd7c11dc63037735b825fb22bf6182f to your computer and use it in GitHub Desktop.
Save ova2/4cd7c11dc63037735b825fb22bf6182f to your computer and use it in GitHub Desktop.
import 'reflect-metadata';
/**
* Every entry point class instance starts its own dependency container.
* Injector ensures that all decorated classes in the container are singletons.
*/
export class Injector extends Map {
public resolve<T>(target: Type<any>): T {
const tokens = Reflect.getMetadata('design:paramtypes', target) || [];
const injections = tokens.map((token: Type<any>) => this.resolve<any>(token));
const classInstance = this.get(target);
if (classInstance) {
return classInstance;
}
const newClassInstance = new target(...injections);
this.set(target, newClassInstance);
console.log(`DI-Container created class ${newClassInstance.constructor.name}`);
return newClassInstance;
}
public release(): void {
for (const value of this.values()) {
if (typeof value['release'] === 'function') {
value['release']();
}
}
this.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment