Simple generic dependency injection library for TypeScript.
Some features:
Intentionally not supported:
For hierarchy, ownership and disposal this library uses @kayahr/scope.
npm install @kayahr/di
Basic example with decorators:
import { injectable, injector } from "@kayahr/di";
@injectable
class MathService {
public add(a: number, b: number): number {
return a + b;
}
}
@injectable({ inject: [ MathService ] })
class Component {
public constructor(private readonly mathService: MathService) {}
public run(): void {
console.log(this.mathService.add(1, 2));
}
}
injector.getSync(Component).run();
Basic example without decorators:
import { injector } from "@kayahr/di";
class MathService {
public add(a: number, b: number): number {
return a + b;
}
}
injector.setClass(MathService);
class Component {
public constructor(private readonly mathService: MathService) {}
public run(): void {
console.log(this.mathService.add(1, 2));
}
}
injector.setClass(Component, { inject: [ MathService ] });
injector.getSync(Component).run();
If you want an isolated injector instance, create one explicitly:
import { Injector } from "@kayahr/di";
const app = new Injector();
The methods on Injector mirror the default injector instance. The injectable decorator is also available on the instance itself:
import { Injector } from "@kayahr/di";
const appInjector = new Injector();
@appInjector.injectable
class AppService {}