Dynamic containerΒΆ

DynamicContainer is a collection of the providers defined in the runtime.

You create the dynamic container instance and put the providers as attributes.

from dependency_injector import containers, providers


if __name__ == '__main__':
    container = containers.DynamicContainer()
    container.factory1 = providers.Factory(object)
    container.factory2 = providers.Factory(object)

    object1 = container.factory1()
    object2 = container.factory2()

    print(container.providers)
    # {
    #     'factory1': <dependency_injector.providers.Factory(...),
    #     'factory2': <dependency_injector.providers.Factory(...),
    # }

The dynamic container is good for the case when your application structure depends on the configuration file or some other source that you can reach only after application is already running (database, api, etc).

In this example we use the configuration to fill in the dynamic container with the providers:

from dependency_injector import containers, providers


class UserService:
    ...


class AuthService:
    ...


def populate_container(container, providers_config):
    for provider_name, provider_info in providers_config.items():
        provided_cls = globals().get(provider_info['class'])
        provider_cls = getattr(providers, provider_info['provider_class'])
        setattr(container, provider_name, provider_cls(provided_cls))


if __name__ == '__main__':
    services_config = {
        'user': {
            'class': 'UserService',
            'provider_class': 'Factory',
        },
        'auth': {
            'class': 'AuthService',
            'provider_class': 'Factory',
        },
    }
    services = containers.DynamicContainer()

    populate_container(services, services_config)

    user_service = services.user()
    auth_service = services.auth()

    assert isinstance(user_service, UserService)
    assert isinstance(auth_service, AuthService)