-
Notifications
You must be signed in to change notification settings - Fork 289
/
inject_self.py
36 lines (22 loc) · 934 Bytes
/
inject_self.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""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()
service1 = providers.Factory(Service, name='Service 1')
service2 = providers.Factory(Service, name='Service 2')
service3 = providers.Factory(Service, name='Service 3')
dispatcher = providers.Singleton(ServiceDispatcher, __self__)
if __name__ == '__main__':
container = Container()
dispatcher = container.dispatcher()
for service in dispatcher.get_services():
print(service.name)