Container class is the core of the dependency injection system. It manages provider registration, dependency resolution, and lifecycle management.
Import
Constructor
Methods
add()
Registers a provider in the container.Parameters
provider- A provider configuration object containing:token: The token to identify the dependencyfactory: A factory function that creates the dependency instancescope(optional): Either"singleton"(default) or"transient"
Example
get()
Retrieves a dependency from the container. Has multiple overloads for different use cases.Parameters
token- The token identifying the dependency to retrieveoptions(optional) - Configuration options:optional: Iftrue, returnsundefinedinstead of throwing when dependency is not foundlazy: Iftrue, returns a function that resolves the dependency when called
Returns
- Without options: The resolved dependency instance
- With
optional: true: The dependency instance orundefined - With
lazy: true: A function that returns the dependency when called - With
lazy: true, optional: true: A function that returns the dependency orundefined
Throws
- Throws an error if the dependency is not registered (unless
optional: true) - Throws an error if a circular dependency is detected
Examples
dispose()
Disposes all singleton instances that implement theDisposable interface.
Returns
A promise that resolves when all disposable singletons have been disposed.Throws
Throws an error if any singleton fails to dispose, collecting all errors into a single error message.Example
Features
Singleton vs Transient Scope
- Singleton (default): The same instance is returned every time
get()is called - Transient: A new instance is created each time
get()is called
Circular Dependency Detection
The container automatically detects circular dependencies and throws an error with a helpful message showing the dependency chain.Resource Cleanup
Singleton instances that implement theDisposable interface will be automatically cleaned up when dispose() is called.