New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Injecting a list of dependencies #243
Comments
@JarnoRFB def to_list(*vargs):
return vargs |
@yandrieiev thanks for the hint. One could also generalize this for other types that take iterables in their contructor. 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 collection_of(collection_type, *args):
return collection_type(args)
def main() -> None:
class IocContainer(containers.DeclarativeContainer):
bs = providers.Factory(collection_of, list, providers.Factory(B, 1), providers.Factory(B, 2))
a = providers.Factory(A, bs)
container = IocContainer()
print(container.a())
if __name__ == "__main__":
main() Probably would be a good idea to document this. |
Hello gentlemen, I would adapt particular case to: 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):
a = providers.Factory(
A,
providers.Factory(B, 1),
providers.Factory(B, 2),
)
container = IocContainer()
print(container.a())
if __name__ == "__main__":
main() The solution is not identical to provided ones. There are two differences:
I like the workaround proposed by @yandrieiev and Roman |
@JarnoRFB @yandrieiev I have created a new provider - dispatcher_factory = providers.Factory(
Dispatcher,
modules=providers.List(
providers.Factory(Module, name='m1'),
providers.Factory(Module, name='m2'),
),
) The original example from this issue now can look like this: class IocContainer(containers.DeclarativeContainer):
bs = providers.List(
providers.Factory(B, 1),
providers.Factory(B, 2),
)
a = providers.Factory(
A,
bs,
)
Roman |
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)
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.
The text was updated successfully, but these errors were encountered: