DI API
Dependency injection container with type-safe service registration and resolution.
What It Does
The DI API provides a type-safe dependency injection container built on awilix. It enables centralized dependency management, service registration with multiple patterns, and lifetime control (singleton/transient) with full TypeScript support.
Key Capabilities
- Type-Safe Container: Generic types for compile-time safety
- Multiple Registration Patterns: useFactory, useClass, useValue
- Lifetime Management: Singleton and transient modes
- Automatic Injection: Factory functions receive dependencies automatically
- Scoped Containers: Create isolated child containers
- Proxy Access: Dot notation for service access
- Environment-Driven Selection: Strategy pattern for multi-provider services
Main Component
DIContainer<Providers>
class DIContainer<Providers> {
static create<T>(): DIContainer<T>
register(registrations: {...}): DIContainer
resolve(provider: keyof Providers): Providers[provider]
createScope(): DIContainer<any>
}Registration Patterns
Factory Pattern
{
useFactory: (container) => new Service(container.dep1),
mode: 'singleton' | 'transient'
}Class Pattern
{
useClass: ServiceClass,
mode: 'singleton' | 'transient'
}Value Pattern
{
useValue: staticValue
}Access Patterns
// Via providers proxy
const service = container.providers.myService
// Via resolve method
const service = container.resolve('myService')Common Use Cases
- Service composition and dependency injection
- Environment-based strategy selection (GCP vs AWS, Mux vs Cloudflare)
- Database connection management
- Singleton service instances
- Testing with isolated scopes
What Customers Don’t Have to Build
- Dependency injection infrastructure
- Service lifetime management
- Automatic dependency resolution
- Type-safe container access
- Factory pattern implementation
- Singleton pattern logic
- Service composition
Last updated on