Dependency Injection
di-typescript is a simple dependency injection framework, which is build upon ts-di and angular/di.js.
Install
npm install di-typescript --save
Configuration
tsconfig.json
file needs the following flags:
"experimentalDecorators": true,
"emitDecoratorMetadata": true
Usage
@Inject
and create an instance
Using The following shows how to inject an instance of UserService
into the constructor of App
.
; ;// resolves UserService by creating an instance or retrieves it, when already exists;
Using factories and tokens
If a dependency should not been resolved from a class but a function or a simple value,
@useFactory
or @useToken
can be used like:
; ;; ; ;;;
Testing and providing different values for specific tokens
When it comes to testing and further a mock should be injected than the actual service, this can be achieved as the following.
;;
Differences between di-typescript and angular/di.js
Compared to ts-di and angular/di.js
di-typescript uses reflect-metadata
to store the meta information. A benefit from using reflect-metadata is, that theInject
decorator don't need parameters anymore. di-typescript retrieves these values
through the design:paramtypes
meta information provided by typescript instead. Another
features are the useFactory
annotation and the angular2-like
{provide: SomeService, useClass/useValue/useFactory}
syntax when creating an injector.