Skip to content

Instantly share code, notes, and snippets.

@LironHazan
Last active April 3, 2020 08:05
Show Gist options
  • Save LironHazan/12c9dab9d68bc5cdd05fab203c1346a5 to your computer and use it in GitHub Desktop.
Save LironHazan/12c9dab9d68bc5cdd05fab203c1346a5 to your computer and use it in GitHub Desktop.
For my blog post about DI
import 'reflect-metadata';
import {Ctr} from "../../../common/types";
export class Injector {
private depInstances: Map<string, Ctr<any>> = new Map<string, Ctr<any>>();
// Not storing an instances map
static resolve<T>(target: Ctr<any>): T {
const tokens = Reflect.getMetadata('design:paramtypes', target) || [];
const injections = tokens.map((token: any) => Injector.resolve<any>(token));
return new target(...injections);
}
// Storing Instances map so a service will only have one instance
resolve (target: Ctr<any>): any {
if (this.depInstances && this.depInstances.has(target.name)) {
console.log(target.name, 'instance exists');
return this.depInstances.get(target.name);
}
const tokens = Reflect.getMetadata('design:paramtypes', target) || [];
const injections = tokens.map((token: any) => Resolver.resolve<any>(token));
this.depInstances.set(target.name, target);
console.log(this.depInstances);
return new target(...injections);
}
}
export const Resolver = new Injector();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment