Simple dependency injector for javascript/typescript which works in IE and doesn't use Proxy.
Inspired by Awilix.
import { DependencyInjector, asValue, asClass, asFunction } from './dependency-injector';
const di = new DependencyInjector();
di.register({
db: asValue('localhost'),
});
const db = di.resolve('db');
// db == localhost
const di = new DependencyInjector();
di.register({
db: asValue('localhost'),
service: asClass(
class Service {
db: string;
constructor(db: string) {
this.db = db;
}
}
),
});
const service = di.resolve('service') as { db: string };
// service.db == localhost
const di = new DependencyInjector();
di.register({
id: asValue(1),
service: asFunction((id: number) => id * 2),
});
const service = di.resolve('service') as number;
// service == 2
Dependencies will be instantiated every time they are resolved. See test for more examples.
- Class and function names can't be mangled, they must be preserved
Registers dependencies as values (asValue), function (asFunction) or classes (asClass)
Resolves dependency
Resolves dependency but returns DepencencyType result
Creates new DepencencyInjector instance from current instance
Dependecies dictionary