{"id":1451,"library":"dependency-injector","title":"Dependency Injector","description":"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.","status":"active","version":"4.49.0","language":"python","source_language":"en","source_url":"https://github.com/ets-labs/python-dependency-injector","tags":["dependency-injection","ioc-container","framework","python3","fastapi","flask","django"],"install":[{"cmd":"pip install dependency-injector","lang":"bash","label":"Install stable version"}],"dependencies":[{"reason":"Required for older Python versions (<3.11) for full typing support.","package":"typing-extensions","optional":true}],"imports":[{"symbol":"containers","correct":"from dependency_injector import containers"},{"symbol":"providers","correct":"from dependency_injector import providers"},{"note":"Use Provide[Container.service] for type hints to correctly mark dependencies for wiring.","wrong":"Provide(Container.service)","symbol":"Provide","correct":"from dependency_injector.wiring import Provide"},{"note":"Since 4.48.1, @inject without explicit Provide[...] markers will raise a warning. Always use `service: Annotated[Service, Provide[Container.service]]` or similar.","wrong":"@inject\ndef my_function(service): ...","symbol":"inject","correct":"from dependency_injector.wiring import inject"}],"quickstart":{"code":"import os\nfrom dependency_injector import containers, providers\nfrom dependency_injector.wiring import Provide, inject\n\n\nclass ConfigService:\n    def __init__(self, api_key: str):\n        self.api_key = api_key\n\n    def get_api_key(self) -> str:\n        return self.api_key\n\n\nclass MyService:\n    def __init__(self, config_service: ConfigService):\n        self.config_service = config_service\n\n    def do_something(self) -> str:\n        api_key = self.config_service.get_api_key()\n        return f\"Doing something with API Key: {api_key[:4]}...\"\n\n\nclass Container(containers.DeclarativeContainer):\n    config = providers.Configuration()\n    config_service = providers.Singleton(\n        ConfigService,\n        api_key=config.api_key\n    )\n    my_service = providers.Factory(\n        MyService,\n        config_service=config_service\n    )\n\n\n@inject\ndef main_app_function(\n    service: MyService = Provide[Container.my_service],\n):\n    print(service.do_something())\n\n\nif __name__ == '__main__':\n    container = Container()\n    # Load configuration from environment variable (or .env file)\n    container.config.api_key.from_env('MY_APP_API_KEY', as_=str, default='default_key_1234567890')\n\n    # Example: Override during testing or development\n    # container.config.api_key.override('test_key_abcde')\n\n    container.wire(modules=[__name__])\n\n    # Set an environment variable for the example to work\n    os.environ['MY_APP_API_KEY'] = os.environ.get('MY_APP_API_KEY', 'example_api_key_12345')\n\n    main_app_function()\n    # Clean up environment variable (optional)\n    del os.environ['MY_APP_API_KEY']\n","lang":"python","description":"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."},"warnings":[{"fix":"Upgrade Python to 3.8 or newer. For Python 3.7, use `dependency-injector<4.47.0`.","message":"Python 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.","severity":"breaking","affected_versions":">=4.47.0"},{"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]`.","message":"Using `@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.","severity":"gotcha","affected_versions":">=4.48.1"},{"fix":"Upgrade to `dependency-injector` 4.49.0 or newer to resolve Pydantic v2 compatibility warnings.","message":"Pydantic v2 deprecation warnings could trigger in `dependency-injector` versions prior to 4.49.0 when using Pydantic for configuration. This was a compatibility issue.","severity":"gotcha","affected_versions":"<4.49.0"},{"fix":"Upgrade to `dependency-injector` 4.47.0 or newer to ensure correct wiring and MRO preservation.","message":"Incorrect monkeypatching during `container.wire()` in versions prior to 4.47.0 could violate Method Resolution Order (MRO) in some classes, leading to unexpected behavior.","severity":"gotcha","affected_versions":"<4.47.0"},{"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.","message":"A 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Performing 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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'callabl':25 'configur':26 'contain':31,60 'cython':54 'declar':28 'depend':1,3,7,16,56 'dependency-inject':55 'django':39,65 'dynam':30 'factori':23 'fastapi':42,63 'featur':20 'flask':40,64 'framework':9,37,61 'help':13 'implement':14 'inject':8,17,57 'injector':2,4 'integr':35 'ioc':59 'ioc-contain':58 'like':21,38 'matur':45 'offer':19 'optim':50 'perform':52 'principl':18 'product':47 'production-readi':46 'provid':22 'python':11 'python3':62 'readi':48 'resourc':27 'singleton':24 'wire':33","created_at":"2026-04-09T03:48:30.153099+00:00","updated_at":"2026-04-16T06:13:21.214304+00:00","problems":[{"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.","cause":"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.","error":"AttributeError: 'Provide' object has no attribute 'some_method'"},{"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.","cause":"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.","error":"ModuleNotFoundError: No module named 'dependency_injector.errors'"},{"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.","cause":"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.","error":"Container has undefined dependencies: \"Container.some_dependency\""},{"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).","cause":"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`.","error":"cannot import name 'providers' from 'dependency_injector'"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"4.49.1","cli_name":"","cli_version":null,"type":"library","homepage":"https://python-dependency-injector.ets-labs.org/","github":"https://github.com/ets-labs/python-dependency-injector","docs":"https://python-dependency-injector.ets-labs.org/","changelog":null,"pypi":"https://pypi.org/project/dependency-injector/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","testing"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"verified"}}