Skip to content

Instantly share code, notes, and snippets.

@L2jLiga
Last active May 26, 2019 08:20
Show Gist options
  • Save L2jLiga/090064af76b046153eb7c448fcf69bfb to your computer and use it in GitHub Desktop.
Save L2jLiga/090064af76b046153eb7c448fcf69bfb to your computer and use it in GitHub Desktop.
Simple DI example
import 'reflect-metadata';
const INSTANCE = Symbol('Getter for injectable instance');
function Injectable(service: any) {
const paramtypes: any[] = Reflect.getMetadata("design:paramtypes", service) || [];
const dependencies = paramtypes.map(type => type[INSTANCE]);
if (dependencies.some(value => value === undefined)) {
throw new Error('Unknown dependency: ???');
}
service[INSTANCE] = new service(...dependencies);
return service;
}
@Injectable
class Logger {
log(msg: string) {
console.log(msg)
}
}
@Injectable
class A {
constructor(private logger: Logger){
}
writeLog() {
this.logger.log(`It works!`);
}
}
// @ts-ignore
A[INSTANCE].writeLog();
{
"scripts": {
"test": "node -r ts-node/register index.ts"
},
"dependencies": {
"@types/node": "^12.0.1",
"reflect-metadata": "^0.1.13",
"ts-node": "^8.1.0",
"typescript": "^3.4.5"
}
}
{
"compilerOptions": {
/* Basic Options */
"target": "es2017",
"module": "commonjs",
/* Experimental Options */
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment