Dict providerΒΆ

Dict provider provides a dictionary of values.

import dataclasses
from typing import Dict

from dependency_injector import containers, providers


@dataclasses.dataclass
class Module:
    name: str


@dataclasses.dataclass
class Dispatcher:
    modules: Dict[str, Module]


class Container(containers.DeclarativeContainer):

    dispatcher_factory = providers.Factory(
        Dispatcher,
        modules=providers.Dict(
            module1=providers.Factory(Module, name='m1'),
            module2=providers.Factory(Module, name='m2'),
        ),
    )


if __name__ == '__main__':
    container = Container()

    dispatcher = container.dispatcher_factory()

    assert isinstance(dispatcher.modules, dict)
    assert dispatcher.modules['module1'].name == 'm1'
    assert dispatcher.modules['module2'].name == 'm2'

    # Call "dispatcher = container.dispatcher_factory()" is equivalent to:
    # dispatcher = Dispatcher(
    #     modules={
    #         'module1': Module(name='m1'),
    #         'module2': Module(name='m2'),
    #     },
    # )

Dict provider handles keyword arguments the same way as a Factory provider.

To use non-string keys or keys with . and - provide a dictionary as a positional argument:

providers.Dict({
    SomeClass: providers.Factory(...),
    'key.with.periods': providers.Factory(...),
    'key-with-dashes': providers.Factory(...),
})

Example:

import dataclasses
from typing import Dict

from dependency_injector import containers, providers


class Command:
    ...


class CommandA(Command):
    ...


class CommandB(Command):
    ...


class Handler:
    ...


class HandlerA(Handler):
    ...


class HandlerB(Handler):
    ...


@dataclasses.dataclass
class Dispatcher:
    command_handlers: Dict[Command, Handler]


class Container(containers.DeclarativeContainer):

    dispatcher_factory = providers.Factory(
        Dispatcher,
        command_handlers=providers.Dict({
            CommandA: providers.Factory(HandlerA),
            CommandB: providers.Factory(HandlerB),
        }),
    )


if __name__ == '__main__':
    container = Container()

    dispatcher = container.dispatcher_factory()

    assert isinstance(dispatcher.command_handlers, dict)
    assert isinstance(dispatcher.command_handlers[CommandA], HandlerA)
    assert isinstance(dispatcher.command_handlers[CommandB], HandlerB)

    # Call "dispatcher = container.dispatcher_factory()" is equivalent to:
    # dispatcher = Dispatcher(
    #     command_handlers={
    #         CommandA: HandlerA(),
    #         CommandB: HandlerB(),
    #     },
    # )