Created
September 11, 2018 19:58
-
-
Save ova2/4cd7c11dc63037735b825fb22bf6182f to your computer and use it in GitHub Desktop.
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
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