2021-02-07 19:13:23 +00:00
|
|
|
"""Container injecting ``self`` example."""
|
|
|
|
|
|
|
|
from dependency_injector import containers, providers
|
|
|
|
|
|
|
|
|
|
|
|
class Service:
|
|
|
|
def __init__(self, name: str):
|
|
|
|
self.name = name
|
|
|
|
|
|
|
|
|
|
|
|
class ServiceDispatcher:
|
|
|
|
def __init__(self, container: containers.Container):
|
|
|
|
self.container = container
|
|
|
|
|
|
|
|
def get_services(self):
|
|
|
|
for provider in self.container.traverse(types=[providers.Factory]):
|
|
|
|
yield provider()
|
|
|
|
|
|
|
|
|
|
|
|
class Container(containers.DeclarativeContainer):
|
|
|
|
|
|
|
|
__self__ = providers.Self()
|
|
|
|
|
2021-09-30 19:16:17 +00:00
|
|
|
service1 = providers.Factory(Service, name="Service 1")
|
|
|
|
service2 = providers.Factory(Service, name="Service 2")
|
|
|
|
service3 = providers.Factory(Service, name="Service 3")
|
2021-02-07 19:13:23 +00:00
|
|
|
|
|
|
|
dispatcher = providers.Singleton(ServiceDispatcher, __self__)
|
|
|
|
|
|
|
|
|
2021-09-30 19:16:17 +00:00
|
|
|
if __name__ == "__main__":
|
2021-02-07 19:13:23 +00:00
|
|
|
container = Container()
|
|
|
|
|
|
|
|
dispatcher = container.dispatcher()
|
|
|
|
for service in dispatcher.get_services():
|
|
|
|
print(service.name)
|