di-corate
v0.2.13
Published
Another dependency injection implementation for Typescript using decorators
Downloads
1,611
Maintainers
Readme
di-corate
Another dependency injection implementation for Typescript using decorators.
Installation
npm install di-corate
Using
Use the library to engage the Dependency Injection in your project.
The library does not use the reflect-metadata
package. The library supports two ways of dependency injection:
- class property
- constructor parameter
Simple DI
service1.ts
import { Injectable } from 'di-corate';
@Injectable()
export class Service1 {
do() {}
}
service2.ts
import { Injectable } from 'di-corate';
@Injectable()
export class Service2 {
run() {}
}
component.ts
import { Injectable, Inject } from 'di-corate';
@Injectable()
export class Component {
// Inject into property.
@Inject(Service1) private readonly srv1: Service1;
// Inejct into constuctor parameter.
constructor(@Inject(Service2) private readonly srv2: Service2) {
srv2.do();
example();
}
private example() {
this.srv1.run();
}
}
Dependency tree
http-client.ts
import { Injectable } from 'di-corate';
@Injectable()
export class HttpClient {
get(url: string) { return 'response'; }
}
service.ts
import { Injectable, Inject } from 'di-corate';
@Injectable()
export class Service {
constructor(@Inject(HttpClient) private readonly http: HttpClient) { }
do() {
const resp = this.http.get('someUrl');
console.log(resp);
}
}
component.ts
import { Injectable, Inject } from 'di-corate';
@Injectable()
export class Component {
constructor(@Inject(Service) private readonly srv: Service) {
example();
}
private example() {
this.srv.do();
}
}
Instance lifetime configuring
Its possible to configure instance lifecycle for each injectale type.
Examples
import { Injectale, InjectionScopeEnum } from 'di-corate';
// Injects as singletone instance.
@Injectale()
export class SomeSingletone {
abstract run(): void;
}
// Injects as singletone instance.
@Injectale({
scope: InjectionScopeEnum.Singletone
})
export class OtherSingletone {
abstract run(): void;
}
// Injects as transient instance.
@Injectale({
scope: InjectionScopeEnum.Transient
})
export class SomeClass {
abstract run(): void;
}
Explanation
Time of instantiation
The moment in time when the dependency instance will be created depends on the chosen dependency injection way.
Custom provider setup
service.ts
export abstract class Service {
abstract run(): void;
}
default-service.ts
import { Injectale } from 'di-corate';
@Injectale()
export class DefaultService implements Service {
run() {
console.log('Implementation');
};
}
component.ts
import { provide, Injectable, Inject } from 'di-corate';
import { DefaultService } from 'default-service';
provide(Service, DefaultService);
@Injectale()
export class Component {
constructor(@Inject('Service') private readonly srv: Service) {
example();
}
private example() {
// Console: 'Implementation'.
this.srv.run();
}
}