Last active
May 26, 2019 08:20
-
-
Save L2jLiga/090064af76b046153eb7c448fcf69bfb to your computer and use it in GitHub Desktop.
Simple DI example
This file contains 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'; | |
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(); |
This file contains 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
{ | |
"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" | |
} | |
} |
This file contains 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
Show hidden characters
{ | |
"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