List providers

List provider provides a list of values.

from dependency_injector import providers


dispatcher_factory = providers.Factory(
    Dispatcher,
    modules=providers.List(
        providers.Factory(Module, name='m1'),
        providers.Factory(Module, name='m2'),
    ),
)

List provider is needed for injecting a list of dependencies. It handles positional argument injections the same way as Factory provider:

  • All providers (instances of Provider) are called every time when injection needs to be done.
  • Providers could be injected “as is” (delegated), if it is defined explicitly. Check out Factory providers delegation.
  • All other values are injected “as is”.
  • Positional context arguments will be appended after List positional injections.

Full example:

import dataclasses
from typing import List

from dependency_injector import providers


@dataclasses.dataclass
class Module:
    """Example module."""

    name: str


@dataclasses.dataclass
class Dispatcher:
    """Example dispatcher."""

    modules: List[Module]


dispatcher_factory = providers.Factory(
    Dispatcher,
    modules=providers.List(
        providers.Factory(Module, name='m1'),
        providers.Factory(Module, name='m2'),
    ),
)

if __name__ == '__main__':
    dispatcher = dispatcher_factory()

    assert isinstance(dispatcher.modules, list)
    assert dispatcher.modules[0].name == 'm1'
    assert dispatcher.modules[1].name == 'm2'

    # Call of dispatcher_factory() is equivalent to:

    dispatcher = Dispatcher(
        modules=[
            Module(name='m1'),
            Module(name='m2'),
        ],
    )

Note

Keyword argument injections are not supported.