1717from injection ._core .common .asynchronous import (
1818 create_semaphore as _create_async_semaphore ,
1919)
20- from injection ._core .scope import Scope , get_active_scopes , get_scope
21- from injection .exceptions import InjectionError
20+ from injection ._core .scope import (
21+ Scope ,
22+ get_scope ,
23+ in_scope_cache ,
24+ remove_scoped_values ,
25+ )
26+ from injection ._core .slots import SlotKey
27+ from injection .exceptions import EmptySlotError , InjectionError
2228
2329
2430@runtime_checkable
@@ -123,7 +129,7 @@ class ScopedInjectable[R, T](Injectable[T], ABC):
123129
124130 @property
125131 def is_locked (self ) -> bool :
126- return any (self in scope . cache for scope in get_active_scopes ( self .scope_name ) )
132+ return in_scope_cache (self , self .scope_name )
127133
128134 @abstractmethod
129135 async def abuild (self , scope : Scope ) -> T :
@@ -143,10 +149,6 @@ def get_instance(self) -> T:
143149 factory = partial (self .build , scope )
144150 return self .logic .get_or_create (scope .cache , self , factory )
145151
146- def setdefault (self , instance : T ) -> T :
147- scope = self .__get_scope ()
148- return self .logic .get_or_create (scope .cache , self , lambda : instance )
149-
150152 def unlock (self ) -> None :
151153 if self .is_locked :
152154 raise RuntimeError (f"To unlock, close the `{ self .scope_name } ` scope." )
@@ -188,8 +190,35 @@ def build(self, scope: Scope) -> T:
188190 return self .factory .call ()
189191
190192 def unlock (self ) -> None :
191- for scope in get_active_scopes (self .scope_name ):
192- scope .cache .pop (self , None )
193+ remove_scoped_values (self , self .scope_name )
194+
195+
196+ @dataclass (repr = False , eq = False , frozen = True , slots = True )
197+ class ScopedSlotInjectable [T ](Injectable [T ]):
198+ cls : type [T ]
199+ scope_name : str
200+ key : SlotKey [T ] = field (default_factory = SlotKey )
201+
202+ @property
203+ def is_locked (self ) -> bool :
204+ return in_scope_cache (self .key , self .scope_name )
205+
206+ async def aget_instance (self ) -> T :
207+ return self .get_instance ()
208+
209+ def get_instance (self ) -> T :
210+ scope_name = self .scope_name
211+ scope = get_scope (scope_name )
212+
213+ try :
214+ return scope .cache [self .key ]
215+ except KeyError as exc :
216+ raise EmptySlotError (
217+ f"The slot for `{ self .cls } ` isn't set in the current `{ scope_name } ` scope."
218+ ) from exc
219+
220+ def unlock (self ) -> None :
221+ remove_scoped_values (self .key , self .scope_name )
193222
194223
195224@dataclass (repr = False , eq = False , frozen = True , slots = True )
0 commit comments