2020-08-21 04:52:12 +03:00
|
|
|
"""Complex example of the injecting of provided instance attributes and items."""
|
|
|
|
|
2020-09-04 00:48:45 +03:00
|
|
|
from dependency_injector import containers, providers
|
2020-08-21 04:52:12 +03:00
|
|
|
|
|
|
|
|
|
|
|
class Service:
|
|
|
|
|
|
|
|
def __init__(self, value):
|
|
|
|
self.value = value
|
|
|
|
|
|
|
|
def get_value(self):
|
|
|
|
return self.value
|
|
|
|
|
|
|
|
|
2020-09-04 00:48:45 +03:00
|
|
|
class Container(containers.DeclarativeContainer):
|
2020-08-21 04:52:12 +03:00
|
|
|
|
2020-09-04 00:48:45 +03:00
|
|
|
service = providers.Singleton(Service, value=42)
|
|
|
|
|
|
|
|
dependency = providers.Object(
|
|
|
|
{
|
2021-09-30 22:32:21 +03:00
|
|
|
"foo": {
|
|
|
|
"bar": 10,
|
|
|
|
"baz": lambda arg: {"arg": arg}
|
2020-09-04 00:48:45 +03:00
|
|
|
},
|
2020-08-21 04:52:12 +03:00
|
|
|
},
|
2020-09-04 00:48:45 +03:00
|
|
|
)
|
2020-08-21 04:52:12 +03:00
|
|
|
|
2020-09-04 00:48:45 +03:00
|
|
|
demo_list = providers.List(
|
2021-09-30 22:32:21 +03:00
|
|
|
dependency.provided["foo"]["bar"],
|
|
|
|
dependency.provided["foo"]["baz"].call(22)["arg"],
|
|
|
|
dependency.provided["foo"]["baz"].call(service)["arg"],
|
|
|
|
dependency.provided["foo"]["baz"].call(service)["arg"].value,
|
|
|
|
dependency.provided["foo"]["baz"].call(service)["arg"].get_value.call(),
|
2020-09-04 00:48:45 +03:00
|
|
|
)
|
2020-08-21 04:52:12 +03:00
|
|
|
|
2020-09-03 00:59:31 +03:00
|
|
|
|
2021-09-30 22:32:21 +03:00
|
|
|
if __name__ == "__main__":
|
2020-09-04 00:48:45 +03:00
|
|
|
container = Container()
|
|
|
|
|
|
|
|
assert container.demo_list() == [
|
2020-08-21 04:52:12 +03:00
|
|
|
10,
|
|
|
|
22,
|
2020-09-04 00:48:45 +03:00
|
|
|
container.service(),
|
2020-08-21 04:52:12 +03:00
|
|
|
42,
|
|
|
|
42,
|
|
|
|
]
|