Registry / web-framework / dependency-injector

dependency-injector

JSON →
library4.49.1pypypi✓ verified 26d ago

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-injector
INSTALL
IMPORT
SIG · DEPENDENCY-INJECTO
D
dependency-injector
web-frameworkpythonv4.49.1
Install
2.3s avg
Import
231ms
Disk
31MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.49.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.242s · 32.6MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.3s · import 0.220s · 33MB
31MB installed
● package 31MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

containers
from dependency_injector import containers
providers
from dependency_injector import providers
Provide
from dependency_injector.wiring import Provide
Provide(Container.service)
Use Provide[Container.service] for type hints to correctly mark dependencies for wiring.
inject
from dependency_injector.wiring import inject
@inject def my_function(service): ...
Since 4.48.1, @inject without explicit Provide[...] markers will raise a warning. Always use `service: Annotated[Service, Provide[Container.service]]` or similar.

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.

import os from dependency_injector import containers, providers from dependency_injector.wiring import Provide, inject class ConfigService: def __init__(self, api_key: str): self.api_key = api_key def get_api_key(self) -> str: return self.api_key class MyService: def __init__(self, config_service: ConfigService): self.config_service = config_service def do_something(self) -> str: api_key = self.config_service.get_api_key() return f"Doing something with API Key: {api_key[:4]}..." class Container(containers.DeclarativeContainer): config = providers.Configuration() config_service = providers.Singleton( ConfigService, api_key=config.api_key ) my_service = providers.Factory( MyService, config_service=config_service ) @inject def main_app_function( service: MyService = Provide[Container.my_service], ): print(service.do_something()) if __name__ == '__main__': container = Container() # Load configuration from environment variable (or .env file) container.config.api_key.from_env('MY_APP_API_KEY', as_=str, default='default_key_1234567890') # Example: Override during testing or development # container.config.api_key.override('test_key_abcde') container.wire(modules=[__name__]) # Set an environment variable for the example to work os.environ['MY_APP_API_KEY'] = os.environ.get('MY_APP_API_KEY', 'example_api_key_12345') main_app_function() # Clean up environment variable (optional) del os.environ['MY_APP_API_KEY']
Debug
Known issues
breakingPython 3.7 support was dropped in version 4.47.0. Users on Python 3.7 or older must upgrade their Python version or stay on an older `dependency-injector` release.
fix
Upgrade Python to 3.8 or newer. For Python 3.7, use `dependency-injector<4.47.0`.
affects: >=4.47.0
gotchaUsing `@inject` decorator without `Provide[...]` markers for parameters will produce a warning since version 4.48.1. This means the framework will not automatically infer which provider to use without the explicit marker.
fix
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]`.
affects: >=4.48.1
gotchaPydantic v2 deprecation warnings could trigger in `dependency-injector` versions prior to 4.49.0 when using Pydantic for configuration. This was a compatibility issue.
fix
Upgrade to `dependency-injector` 4.49.0 or newer to resolve Pydantic v2 compatibility warnings.
affects: <4.49.0
gotchaIncorrect monkeypatching during `container.wire()` in versions prior to 4.47.0 could violate Method Resolution Order (MRO) in some classes, leading to unexpected behavior.
fix
Upgrade to `dependency-injector` 4.47.0 or newer to ensure correct wiring and MRO preservation.
affects: <4.47.0
gotchaA common anti-pattern in Dependency Injection is having longer-lived services (e.g., Singletons) depend on shorter-lived services (e.g., Factories, Resources intended per-request). This 'captive dependency' can lead to stale data, resource leaks, or unexpected behavior in concurrent applications.
fix
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.
affects: All versions
gotchaPerforming blocking I/O or computationally heavy operations within Provider definitions or Module `configure` methods can introduce performance bottlenecks or deadlocks, as `dependency-injector` uses internal locks for thread safety during container initialization.
fix
Defer heavy operations and I/O to the actual service methods, not their construction or configuration. Providers should primarily focus on assembling dependencies quickly.
affects: All versions
Errors
Common errors & fixes
AttributeError: 'Provide' object has no attribute 'some_method'
This error occurs when the `dependency-injector`'s wiring mechanism has not correctly injected the actual service instance, leaving the `Provide` marker object in its place. This typically happens if `container.wire()` is not called, or if the module containing the `@inject` decorated function/method is not included in the `modules` or `packages` argument of `container.wire()` at application startup.
fix
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.
ModuleNotFoundError: No module named 'dependency_injector.errors'
This error indicates that Python cannot find the `errors` submodule within the `dependency_injector` package. This can be caused by an incomplete or corrupted installation of the library, or issues with environment packaging tools like PyInstaller that might not correctly bundle all submodules.
fix
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.
Container has undefined dependencies: "Container.some_dependency"
This error is raised when a `Dependency` provider is declared within a container but is never explicitly provided (e.g., via `provider.override()`) or given a default value before the container attempts to resolve it. The `Dependency` provider acts as a placeholder for a dependency that will be defined later.
fix
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.
cannot import name 'providers' from 'dependency_injector'
This error occurs due to an incorrect import statement. The `providers` submodule is not directly available under the top-level `dependency_injector` package. Instead, specific providers like `Factory`, `Singleton`, `Callable`, etc., are imported from `dependency_injector.providers`, and containers are imported from `dependency_injector.containers`.
fix
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).
Upgrade
Version history
4.49.1latest on PyPI · released Jun 18, 2026
Audit
Dependencies
typing-extensionsoptionalRequired for older Python versions (<3.11) for full typing support.
Agent activity
13 hits · last 30 days
node
12
Resources