inject() function retrieves dependencies from the current injection context. It must be called within a factory function registered in a container.
Import
Signature
Parameters
token- The token identifying the dependency to injectoptions(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 called outside of an injection context
- Throws an error if the dependency is not registered (unless
optional: true) - Throws an error if a circular dependency is detected
Usage
Basic Injection
Inject required dependencies in factory functions:Optional Dependencies
Use theoptional flag to handle dependencies that may not be registered:
Lazy Injection
Use thelazy flag to defer dependency resolution until it’s actually needed:
- Breaking circular dependencies
- Deferring expensive initialization
- Conditional dependency resolution
Combining Lazy and Optional
You can combine both flags for maximum flexibility:Injection Context
Theinject() function must be called within an injection context, which is automatically created when:
- A factory function is executed by the container
- Dependencies are being resolved during
container.get()
inject() outside of these contexts will throw an error: