@canale/dependency-injection
v5.0.0
Published
Extremely simple, singleton based, dependency injection framework
Downloads
17
Readme
@canale/dependency-injection
A simplistic dependency injection framework that can be used with TypeScript decorators.
Installation
yarn add @canale/dependency-injection
Usage
1. Define type information
This framework allows for some level of type checking. To add type information to your dependencies, you can augment the Dependencies
interface:
declare module '@canale/dependency-injection/lib/types' {
interface Dependencies {
db: MongoClient;
eventBus: EventBus;
server: Server;
// ...
}
}
2. Register your dependencies
import { register, registerAll } from '@canale/dependency-injection';
register('db', myMongoClient);
register('eventBus', EventBusClass);
register('server', () => initServer());
// or
registerAll({
db: myMongoClient,
eventBus: EventBusClass,
server: () => initServer(),
});
3. Load your dependencies
This can be done manually:
import { getDependency } from '@canale/dependency-injection';
const db = getDependency('db');
Or through annotations:
import { inject, injectNamed, injectable } from '@canale/dependency-injection';
@injectable
class MyClass {
@inject
private readonly db!: MongoClient;
// OR
@injectNamed('db')
private readonly myDbClient!: MongoClient;
}