2
2
from dependency_injector .wiring import inject , Provide , Closing
3
3
4
4
5
+ class Singleton :
6
+ pass
7
+
8
+
5
9
class Service :
6
10
init_counter : int = 0
7
11
shutdown_counter : int = 0
12
+ dependency : Singleton = None
8
13
9
14
@classmethod
10
15
def reset_counter (cls ):
11
16
cls .init_counter = 0
12
17
cls .shutdown_counter = 0
13
18
14
19
@classmethod
15
- def init (cls ):
20
+ def init (cls , dependency : Singleton = None ):
21
+ if dependency :
22
+ cls .dependency = dependency
16
23
cls .init_counter += 1
17
24
18
25
@classmethod
@@ -37,11 +44,36 @@ def init_service():
37
44
service .shutdown ()
38
45
39
46
47
+ def init_service_with_singleton (singleton : Singleton ):
48
+ service = Service ()
49
+ service .init (singleton )
50
+ yield service
51
+ service .shutdown ()
52
+
53
+
40
54
class Container (containers .DeclarativeContainer ):
41
55
42
56
service = providers .Resource (init_service )
43
57
factory_service = providers .Factory (FactoryService , service )
44
- factory_service_kwargs = providers .Factory (FactoryService , service = service )
58
+ factory_service_kwargs = providers .Factory (
59
+ FactoryService ,
60
+ service = service
61
+ )
62
+ nested_service = providers .Factory (NestedService , factory_service )
63
+
64
+
65
+ class ContainerSingleton (containers .DeclarativeContainer ):
66
+
67
+ singleton = providers .Resource (Singleton )
68
+ service = providers .Resource (
69
+ init_service_with_singleton ,
70
+ singleton
71
+ )
72
+ factory_service = providers .Factory (FactoryService , service )
73
+ factory_service_kwargs = providers .Factory (
74
+ FactoryService ,
75
+ service = service
76
+ )
45
77
nested_service = providers .Factory (NestedService , factory_service )
46
78
47
79
0 commit comments