Dependency Injector

4.49.0 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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']

view raw JSON →