From 88e83db330604886fc7eb3b4f3eaa4f8f212e179 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Sun, 31 Jul 2022 13:32:02 +0200 Subject: [PATCH] Improved scope handling --- src/cpl_core/dependency_injection/scope.py | 7 +++++++ src/cpl_core/dependency_injection/scope_abc.py | 2 +- src/tests/custom/general/src/general/application.py | 5 +++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/cpl_core/dependency_injection/scope.py b/src/cpl_core/dependency_injection/scope.py index a461fcdd..14531e66 100644 --- a/src/cpl_core/dependency_injection/scope.py +++ b/src/cpl_core/dependency_injection/scope.py @@ -9,6 +9,13 @@ class Scope(ScopeABC): def __init__(self, service_provider: ServiceProviderABC): self._service_provider = service_provider self._service_provider.set_scope(self) + ScopeABC.__init__(self) + + def __enter__(self): + return self + + def __exit__(self, *args): + self.dispose() @property def service_provider(self) -> ServiceProviderABC: diff --git a/src/cpl_core/dependency_injection/scope_abc.py b/src/cpl_core/dependency_injection/scope_abc.py index 4de16c74..daf76d13 100644 --- a/src/cpl_core/dependency_injection/scope_abc.py +++ b/src/cpl_core/dependency_injection/scope_abc.py @@ -18,7 +18,7 @@ class ScopeABC(ABC): pass @abstractmethod - def dispose(): + def dispose(self): r"""Sets service_provider to None """ pass \ No newline at end of file diff --git a/src/tests/custom/general/src/general/application.py b/src/tests/custom/general/src/general/application.py index d83d569b..9de4ae6c 100644 --- a/src/tests/custom/general/src/general/application.py +++ b/src/tests/custom/general/src/general/application.py @@ -53,4 +53,9 @@ class Application(ApplicationABC): ip_pipe2: IPAddressPipe = self._services.get_service(IPAddressPipe) Console.write_line(f'DI working: {test == test2 and ip_pipe != ip_pipe2}') Console.write_line(self._services.get_service(LoggerABC)) + + scope = self._services.create_scope() + Console.write_line('scope', scope) + with self._services.create_scope() as s: + Console.write_line('with scope', s) # self.test_send_mail()