loose-di
v5.0.0
Published
Lightweight dependency injection container for JavaScript/Node.js. Supports InjectionToken, @Optional, multi-provider, plugin-based extensions, lifecycle hooks, property injection, class/factory/value providers, singleton/request/transient scopes, async r
Maintainers
Readme
loose-di
Lightweight dependency injection container for JavaScript/Node.js.
Features (v5)
- Class, factory, and value providers
InjectionToken— descriptive typed tokens@Optional— optional dependencies (returnsundefinedif unregistered)multi: true/container.getAll()— multiple providers for one token- Plugin-based container extensions (resolve middleware, hooks)
- Lifecycle hooks:
onInit(after deps injected) andonDestroy(on container shutdown) - Property injection (
@Injecton properties,$injectPropsstatic, orpropsin provider config) - Scopes: singleton (default), request, transient
- Module system with imports
- Async providers (factory can return Promise)
- Cyclic dependency detection
@Injectable/@Injectdecorators$inject/$injectPropsstatic properties (no decorators needed)- Request-scoped container fork +
container.getOptional()/container.getAll()
Usage
const { Container, InjectionToken, defineModule } = require('loose-di');
const DB = new InjectionToken('Database');
const container = new Container();
container.provide({ token: DB, useFactory: async () => await createConnection() });
container.provide({ token: 'Config', useValue: { port: 3000 } });
// Optional dependency
class Logger {
constructor(@Inject(DB) @Optional() db) {
this.db = db; // undefined if DB not provided
}
}
// Multi-provider (multiple values for same token)
container.provide({ token: 'Plugin', useValue: pluginA, multi: true });
container.provide({ token: 'Plugin', useValue: pluginB, multi: true });
const plugins = await container.getAll('Plugin'); // [pluginA, pluginB]
const db = await container.get(DB);
const maybe = await container.getOptional('Missing'); // undefinedRoadmap
| Version | Feature | |---------|---------| | v1 | Basic DI (class/factory/value, scopes, modules, cyclic detection) | | v2 | Property injection | | v3 | Lifecycle hooks (onInit, onDestroy) | | v4 | Plugin-based container extensions | | v5 | InjectionToken, @Optional, multi-provider |
