88from ellar .common .utils .functional import SimpleLazyObject , empty
99from ellar .core import Config
1010from ellar .di import EllarInjector
11+ from ellar .events import app_context_started_events , app_context_teardown_events
1112
1213if t .TYPE_CHECKING :
1314 from ellar .app .main import App
1415
15- _application_context : ContextVar [
16+ app_context_var : ContextVar [
1617 t .Optional [t .Union ["ApplicationContext" , t .Any ]]
1718] = ContextVar ("ellar.app.context" )
1819
@@ -48,14 +49,15 @@ def config(self) -> Config:
4849 return self ._config
4950
5051 def __enter__ (self ) -> "ApplicationContext" :
51- app_context = _application_context .get (empty )
52+ app_context = app_context_var .get (empty )
5253 if app_context is empty :
5354 # If app_context exist
54- _application_context .set (self )
55+ app_context_var .set (self )
5556 if current_config ._wrapped is not empty : # pragma: no cover
5657 # ensure current_config is in sync with running application context.
5758 current_config ._wrapped = self .config
5859 app_context = self
60+ app_context_started_events .run ()
5961 return app_context # type:ignore[return-value]
6062
6163 def __exit__ (
@@ -64,7 +66,8 @@ def __exit__(
6466 exc_value : t .Optional [BaseException ],
6567 tb : t .Optional [TracebackType ],
6668 ) -> None :
67- _application_context .set (empty )
69+ app_context_teardown_events .run ()
70+ app_context_var .set (empty )
6871
6972 current_app ._wrapped = empty # type:ignore[attr-defined]
7073 current_injector ._wrapped = empty # type:ignore[attr-defined]
@@ -76,23 +79,23 @@ def create(cls, app: "App") -> "ApplicationContext":
7679
7780
7881def _get_current_app () -> "App" :
79- app_context = _application_context .get (empty )
82+ app_context = app_context_var .get (empty )
8083 if app_context is empty :
8184 raise RuntimeError ("ApplicationContext is not available at this scope." )
8285
8386 return app_context .app # type:ignore[union-attr]
8487
8588
8689def _get_injector () -> EllarInjector :
87- app_context = _application_context .get (empty )
90+ app_context = app_context_var .get (empty )
8891 if app_context is empty :
8992 raise RuntimeError ("ApplicationContext is not available at this scope." )
9093
9194 return app_context .injector # type:ignore[union-attr]
9295
9396
9497def _get_application_config () -> Config :
95- app_context = _application_context .get (empty )
98+ app_context = app_context_var .get (empty )
9699 if app_context is empty :
97100 config_module = os .environ .get (ELLAR_CONFIG_MODULE )
98101 if not config_module :
0 commit comments