Provider<T> interface defines the configuration for registering dependencies in the container.
Import
Interface
Properties
token
prototype and name properties.
See Token for more details.
Example
factory
- Must return an instance of type
T - Can use
inject()to request other dependencies - Is executed within an injection context
- Should not have side effects outside of instance creation
Example
scope (optional)
"singleton" if not specified.
"singleton"(default): The factory is called once, and the same instance is returned for all subsequent requests"transient": The factory is called every time the dependency is requested, creating a new instance each time
Example
Usage
Basic Provider
The simplest provider just needs a token and a factory:Provider with Dependencies
Useinject() in the factory to request other dependencies:
Singleton Provider
Singleton scope ensures only one instance exists:Transient Provider
Transient scope creates a new instance each time:Provider with Symbol Token
Use symbols for non-class dependencies:Factory with Complex Logic
The factory can contain any initialization logic:Type Safety
TheProvider<T> interface is generic, ensuring type safety between the token and factory: