Skip to content

Injecting a list of dependencies #243

@JarnoRFB

Description

@JarnoRFB

Hi, thanks for the nice and well documented framework! There is one point I am currently missing. Let's say I have a class that depends on a list of other classes, I want to achieve something like the following example (written in Python 3.7)

from typing import *
from dependency_injector import containers, providers


class B:
    def __init__(self, val: int):
        self.val = val

    def __repr__(self):
        return f"B({self.val})"


class A:
    def __init__(self, bs: List[B]):
        self.bs = bs

    def __repr__(self):
        return f"A({self.bs})"


def main() -> None:
    class IocContainer(containers.DeclarativeContainer):
        bs = providers.Provider(
            list,
            providers.Factory(B, 1),
            providers.Factory(B, 2),

        )

        a = providers.Factory(
            A,
            bs,
        )

    container = IocContainer()

    print(container.a())


if __name__ == "__main__":
    main()

However, using a list of providers seems not to be possible, as the list constructor only takes a single argument, but directly instantiating a list of providers will not instantiate the providers.
What would be the way to go to inject a list of dependencies.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions