{"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":"en","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,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}