Dependency Injector is a dependency injection framework for Python. It helps implement the dependency injection principle, offering features like providers (Factory, Singleton, Callable, Configuration, Resource), declarative and dynamic containers, and wiring for integration with frameworks like Django, Flask, and FastAPI. It is mature, production-ready, and optimized for performance with Cython.
pip install dependency-injectorVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates defining a container with a Configuration provider, a Singleton service, and a Factory service. It shows how to inject dependencies into a function using `@inject` and `Provide` and how to configure values from environment variables.
Upgrade Python to 3.8 or newer. For Python 3.7, use `dependency-injector<4.47.0`.
Ensure all parameters to `@inject`-decorated functions/methods that require injection use `param_name: Annotated[Type, Provide[Container.provider_name]]` or `param_name: Type = Provide[Container.provider_name]`.
Upgrade to `dependency-injector` 4.49.0 or newer to resolve Pydantic v2 compatibility warnings.
Upgrade to `dependency-injector` 4.47.0 or newer to ensure correct wiring and MRO preservation.
Carefully manage provider lifetimes. Avoid injecting 'Factory' or 'Resource' providers directly into 'Singleton' providers if their instance state should not be shared across the entire application lifecycle. Consider injecting a factory *callable* or creating a new scope explicitly if a fresh instance of the short-lived dependency is needed within the singleton.
Defer heavy operations and I/O to the actual service methods, not their construction or configuration. Providers should primarily focus on assembling dependencies quickly.
Ensure that the `container.wire()` method is called early in your application's lifecycle, and that the `modules` or `packages` argument correctly points to the Python modules or packages where injections are expected. For example, `container.wire(modules=[__name__])` for the current module, or `container.wire(packages=['your_app.services'])` for a package.
First, try reinstalling the library: `pip uninstall dependency-injector` followed by `pip install dependency-injector`. If using PyInstaller, ensure that `dependency_injector.errors` is explicitly included in hidden imports, e.g., by adding `--hidden-import=dependency_injector.errors` to your PyInstaller command.
Either provide the dependency later using `container.some_dependency.override(some_provider)` or ensure that a default provider or value is set for the `Dependency` provider if it's meant to be optional.
Change the import statement to import specific providers or the `containers` submodule directly. For example: `from dependency_injector import containers, providers` is incorrect. It should be `from dependency_injector import containers` and `from dependency_injector.providers import Factory, Singleton` (or other specific providers).