2020-10-22 18:49:39 +00:00
|
|
|
"""`Dict` provider example."""
|
|
|
|
|
|
|
|
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(
|
2021-09-30 19:32:21 +00:00
|
|
|
module1=providers.Factory(Module, name="m1"),
|
|
|
|
module2=providers.Factory(Module, name="m2"),
|
2020-10-22 18:49:39 +00:00
|
|
|
),
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-09-30 19:32:21 +00:00
|
|
|
if __name__ == "__main__":
|
2020-10-22 18:49:39 +00:00
|
|
|
container = Container()
|
|
|
|
|
|
|
|
dispatcher = container.dispatcher_factory()
|
|
|
|
|
|
|
|
assert isinstance(dispatcher.modules, dict)
|
2021-09-30 19:32:21 +00:00
|
|
|
assert dispatcher.modules["module1"].name == "m1"
|
|
|
|
assert dispatcher.modules["module2"].name == "m2"
|
2020-10-22 18:49:39 +00:00
|
|
|
|
|
|
|
# Call "dispatcher = container.dispatcher_factory()" is equivalent to:
|
|
|
|
# dispatcher = Dispatcher(
|
|
|
|
# modules={
|
2021-09-30 19:32:21 +00:00
|
|
|
# "module1": Module(name="m1"),
|
|
|
|
# "module2": Module(name="m2"),
|
2020-10-22 18:49:39 +00:00
|
|
|
# },
|
|
|
|
# )
|