TSNODE-DI
Simple and lightweight dependency injection for Node TypeScript.
Getting Started
Installation
npm install --save tsnode-di
Usage
import { Injector } from 'tsnode-di';
import { Injectable } from 'tsnode-di';
@Injectable()
class ProviderClass {
private aId: number;
constructor() {
this.aId = Math.ceil(Math.random() * 100000);
}
public get id(): number {
return this.aId;
}
}
@Injectable()
class ConsumerClass1 {
constructor(public provider: ProviderClass) { }
public get provider():ProviderClass {
return this.provider;
}
}
@Injectable()
class ConsumerClass2 {
@Resolve(ProviderClass)
public provider: ProviderClass;
constructor() { }
public get provider():ProviderClass {
return this.provider;
}
}
const obj1 = Injector.resolve<ConsumerClass1>(ConsumerClass1);
const obj2 = Injector.resolve<ConsumerClass2>(ConsumerClass2);
if(obj1.provider.id !== obj2.provider.id)
throw new Error("DI Failed!");