@resolid/di package provides a lightweight, fully-typed dependency injection container for TypeScript. It helps you manage dependencies, control object lifecycles, and build testable applications.
Installation
Basic Usage
The fundamental workflow involves creating a container, registering providers, and resolving dependencies:Core Concepts
Container
TheContainer class is the main orchestrator for dependency injection. It stores providers and manages instance lifecycles.
Methods:
add(provider: Provider): void- Register a providerget<T>(token: Token<T>): T- Resolve a dependencydispose(): Promise<void>- Clean up all singleton instances
Tokens
Tokens uniquely identify dependencies in the container. They can be:- Classes: Use the class constructor as the token
- Symbols: Use
Symbol()for abstract dependencies - Strings: Use string identifiers (less type-safe)
Providers
A provider defines how to create an instance of a dependency:The inject() Function
The inject() function resolves dependencies within a factory function. It must be called inside a provider’s factory:
Scopes
Scopes control the lifecycle of resolved dependencies.Singleton Scope (Default)
Only one instance is created and shared across all resolutions:Transient Scope
A new instance is created for every resolution:Advanced Features
Optional Dependencies
Resolve dependencies that may not be registered:Lazy Resolution
Defer dependency resolution until it’s actually needed:- Breaks circular dependencies
- Improves startup performance
- Enables conditional dependency usage
Circular Dependency Detection
The container automatically detects and prevents circular dependencies:Disposable Resources
Manage resource cleanup with thedispose() method:
API Reference
Container Class
See source atpackages/di/src/container/index.ts:12
inject Function
See source atpackages/di/src/inject/index.ts:4
Types
Best Practices
1. Use Class Tokens When Possible
2. Prefer Singleton for Services
Most services should be singletons to share state and reduce memory usage:3. Use Transient for Stateful Objects
Use transient scope for objects that hold per-request state:4. Implement dispose() for Resources
Always implementdispose() for services that manage resources: