defget_type_dependencies(self,_type:type)->list[ConstructorDependency]:""" Inspect __init__ signature to auto-discover constructor dependencies. """params=get_signature(_type).parametersdeps=[]forname,paraminparams.items():ifparam.annotation==inspect.Parameter.empty:raiseMissingAnnotationError(f"Missing type annotation for parameter '{name}' in {_type.__name__}")deps.append(ConstructorDependency(name=name,_type=param.annotation))returndeps
defadd(self,dependency_type:type,implementation_type:Optional[type]=None,**kwargs):""" Shorthand to register a service (default: Transient). """kwargs.setdefault('lifetime',Lifetime.Transient)self._register_dependency(dependency_type,implementation_type,**kwargs)
defadd_singleton(self,dependency_type:type,implementation_type:Optional[type]=None,instance:Any=None,factory:Callable=None,eager:bool=False)->None:""" Register a singleton service. `eager`: If True, construct the singleton during build()/build_async() instead of lazily on first resolve(). """self._register_dependency(dependency_type=dependency_type,implementation_type=implementation_type,lifetime=Lifetime.Singleton,instance=instance,factory=factory,eager=eager)
defadd_transient(self,dependency_type:type,implementation_type:Optional[type]=None,factory:Callable=None)->None:"""Register a transient service."""self._register_dependency(dependency_type=dependency_type,implementation_type=implementation_type,lifetime=Lifetime.Transient,factory=factory)
defadd_scoped(self,dependency_type:type,implementation_type:Optional[type]=None,factory:Callable=None)->None:"""Register a scoped service."""self._register_dependency(dependency_type=dependency_type,implementation_type=implementation_type,lifetime=Lifetime.Scoped,factory=factory)
defregister_many(self,types:list[type],lifetime:str=Lifetime.Transient):""" Bulk-register multiple types with the same lifetime. """fortintypes:self._register_dependency(dependency_type=t,implementation_type=None,lifetime=lifetime)
Finalize registrations and return a built ServiceProvider.
eager_all: If True, mark every singleton registration as eager so
all singletons are constructed during build() (pre-lazy behavior),
instead of only those explicitly registered with eager=True.
Source code in packages/depi-core/depi/services.py
defbuild_provider(self,eager_all:bool=False)->'ServiceProvider':""" Finalize registrations and return a built ServiceProvider. `eager_all`: If True, mark every singleton registration as eager so all singletons are constructed during build() (pre-lazy behavior), instead of only those explicitly registered with eager=True. """ifeager_all:forreginself._container.values():ifreg.lifetime==Lifetime.Singleton:reg.eager=Trueprovider=ServiceProvider(self)provider.build()returnprovider
def__init__(self,service_collection:ServiceCollection):self._service_collection=service_collectionself._dependency_lookup=service_collection.get_container()self._dependencies=list(self._dependency_lookup.values())self._singleton_instances:dict[type,Any]={}self._cache:dict={}# RLock (not Lock) is required: singleton A's constructor may call# resolve(B) while this lock is held. RLock lets the same thread# re-enter, preventing deadlock during recursive singleton construction.self._cache_lock=RLock()# Per-type asyncio.Lock objects for coroutine-safe lazy singleton# creation. Lazily populated; the dict itself is protected by a small# sync Lock held only while reading or inserting lock objects.self._async_singleton_locks:dict[type,asyncio.Lock]={}self._async_lock_dict_lock=Lock()self._initialize_provider()
defresolve(self,_type:type)->Any:""" Resolve a registered service synchronously. Optimized with fast path for singletons and minimal locking. """reg=self._get_registered_dependency(_type)lifetime=reg.lifetimeiflifetime==Lifetime.Singleton:# Use registration.dependency_type as the consistent cache key.dep_type=reg.dependency_typecache=self._singleton_instancesinstance=cache.get(dep_type)ifinstanceisnotNone:returninstance# RLock allows the same thread to re-enter while constructing a# singleton whose constructor itself calls resolve() for another# singleton (e.g. A.__init__ calls resolve(B)).withself._cache_lock:instance=cache.get(dep_type)ifinstanceisnotNone:returninstanceifreg.factory:instance=reg.factory(self)ifinspect.isawaitable(instance):_reject_awaitable(_type,instance)elifreg.instanceisnotNone:instance=reg.instanceelse:instance=reg.activate(self)cache[dep_type]=instancereturninstanceeliflifetime==Lifetime.Transient:ifreg.factory:instance=reg.factory(self)ifinspect.isawaitable(instance):_reject_awaitable(_type,instance)returninstancereturnreg.activate(self)eliflifetime==Lifetime.Scoped:raiseScopeRequiredError("Scoped resolution requires a scope. Call provider.create_scope().")raiseUnknownLifetimeError(f"Unknown lifetime: {lifetime}")
asyncdefresolve_async(self,_type:type)->Any:""" Resolve a registered service asynchronously. Optimized with fast path for singletons and minimal locking. """reg=self._get_registered_dependency(_type)ifreg.lifetime==Lifetime.Singleton:# Use registration.dependency_type as the consistent cache key.dep_type=reg.dependency_type# Fast path: lock-free cache check (covers 99% of singleton calls)instance=self._singleton_instances.get(dep_type)ifinstanceisnotNone:returninstance# Per-type asyncio.Lock is required for coroutine-safe lazy singleton# construction. A single global async lock would deadlock when singleton# A's constructor awaits resolve_async(B) — both would compete for the# same lock. Per-type locks let independent singletons be built# concurrently without blocking each other.## The dict lock is held only long enough to read or create the asyncio.Lock# object; it is never held across an await.withself._async_lock_dict_lock:lock=self._async_singleton_locks.get(dep_type)iflockisNone:lock=asyncio.Lock()self._async_singleton_locks[dep_type]=lockasyncwithlock:# Double-check after acquiring the per-type async lock.instance=self._singleton_instances.get(dep_type)ifinstanceisnotNone:returninstanceifreg.factory:inst=reg.factory(self)ifinspect.isawaitable(inst):inst=awaitinstinstance=instelifreg.instanceisnotNone:# Pre-built during build() phaseinstance=reg.instanceelse:# Lazy singleton via async constructor injectioninstance=awaitreg.activate_async(self)self._singleton_instances[dep_type]=instancereturninstanceelifreg.lifetime==Lifetime.Transient:ifreg.factory:inst=reg.factory(self)returnawaitinstifinspect.isawaitable(inst)elseinstelse:returnawaitreg.activate_async(self)elifreg.lifetime==Lifetime.Scoped:raiseScopeRequiredError("Scoped resolution requires a scope. Call provider.create_scope().")raiseUnknownLifetimeError(f"Unknown lifetime: {reg.lifetime}")
Integrations use this to decide whether an annotated view-function
parameter is something depi owns, or something the web framework will
supply (a path converter, a query argument).
Source code in packages/depi-core/depi/services.py
defis_registered(self,_type:type)->bool:""" Return True if ``_type`` has a registration. Integrations use this to decide whether an annotated view-function parameter is something depi owns, or something the web framework will supply (a path converter, a query argument). """return_typeinself._dependency_lookup
Validate and order every singleton registration, but only construct
factories and singletons explicitly marked eager=True. Other
singletons are validated/ordered here and constructed lazily on
first resolve().
Source code in packages/depi-core/depi/services.py
defbuild(self)->'ServiceProvider':""" Validate and order every singleton registration, but only construct factories and singletons explicitly marked eager=True. Other singletons are validated/ordered here and constructed lazily on first resolve(). """# Validate dependencies before buildingself._validate_dependencies()# whole-graph cycle check across every lifetime (lenient on missing deps)self._walk_dependencies(self._dependencies,strict=False,collect_order=False)to_build=[dfordinself._dependenciesifd.lifetime==Lifetime.Singleton]# strict ordered pass validates/orders all singletons, even lazy onessorted_deps=self._walk_dependencies(to_build,strict=True,collect_order=True)forreginsorted_deps:ifnot(reg.factoryorreg.eager):continueifreg.instanceisNone:ifreg.factory:inst=reg.factory(self)# support coroutine factoriesifasyncio.iscoroutine(inst):try:# Probe only: raises RuntimeError when there is no# running loop, which the except branch below handles.asyncio.get_running_loop()# run in separate thread if already in event loopimportconcurrent.futureswithconcurrent.futures.ThreadPoolExecutor()asex:inst=ex.submit(asyncio.run,inst).result()exceptRuntimeError:inst=asyncio.run(inst)else:inst=reg.activate(self)reg.instance=instwithself._cache_lock:self._singleton_instances[reg.dependency_type]=reg.instancereturnself
asyncdefbuild_async(self)->'ServiceProvider':""" Async variant of build(): validates/orders every singleton, but only constructs factories and singletons explicitly marked eager=True. """# Validate dependencies before buildingself._validate_dependencies()# whole-graph cycle check across every lifetime (lenient on missing deps)self._walk_dependencies(self._dependencies,strict=False,collect_order=False)to_build=[dfordinself._dependenciesifd.lifetime==Lifetime.Singleton]# strict ordered pass validates/orders all singletons, even lazy onessorted_deps=self._walk_dependencies(to_build,strict=True,collect_order=True)forreginsorted_deps:ifnot(reg.factoryorreg.eager):continueifreg.instanceisNone:ifreg.factory:inst=reg.factory(self)ifasyncio.iscoroutine(inst):inst=awaitinstelse:inst=awaitreg.activate_async(self)reg.instance=instwithself._cache_lock:self._singleton_instances[reg.dependency_type]=reg.instancereturnself
Singletons cascade to the root provider; scoped services return the
one instance held by this scope (constructing it on first request);
transients are built fresh on every call.
defresolve(self,_type:type)->Any:""" Resolve ``_type`` against this scope. Singletons cascade to the root provider; scoped services return the one instance held by this scope (constructing it on first request); transients are built fresh on every call. Raises: UnregisteredDependencyError: ``_type`` has no registration. AsyncFactoryError: ``_type`` has an async factory; use ``resolve_async``. """provider=self._providerreg=provider._get_registered_dependency(_type)life=reg.lifetime# Singleton always via root provideriflife==Lifetime.Singleton:returnprovider.resolve(_type)insts=self._scoped_instances# Scoped: return cached if presentiflife==Lifetime.Scoped:inst=insts.get(_type)ifinstisnotNone:returninst# Transient or new Scoped instancefactory=reg.factoryiffactory:inst=factory(self)# Same guard ServiceProvider.resolve applies. Without it an async# factory resolved through a scope returns an un-awaited coroutine,# which then fails far away from its cause -- and scopes are what# every web integration resolves through.ifinspect.isawaitable(inst):_reject_awaitable(_type,inst)else:# your precompiled sync resolverinst=reg._resolver_fn(self)# Cache scopediflifeisLifetime.Scoped:insts[_type]=instreturninst
Awaits async factories and async constructor dependencies. Scoped
instances are cached for the life of the scope, so a repeated
resolution returns the same object without re-awaiting.
asyncdefresolve_async(self,_type:type)->Any:""" Async variant of ``resolve``. Awaits async factories and async constructor dependencies. Scoped instances are cached for the life of the scope, so a repeated resolution returns the same object without re-awaiting. Raises: UnregisteredDependencyError: ``_type`` has no registration. """provider=self._providerreg=provider._get_registered_dependency(_type)life=reg.lifetime# Singleton via root provideriflifeisLifetime.Singleton:returnawaitprovider.resolve_async(_type)insts=self._scoped_instances# Scoped: return cached if presentiflifeisLifetime.Scoped:inst=insts.get(_type)ifinstisnotNone:returninst# Transient or new Scoped instancefactory=reg.factoryiffactory:inst=factory(self)ifasyncio.iscoroutine(inst):inst=awaitinstelse:# fall back to the generic async activationinst=awaitreg.activate_async(self)# Cache scopediflifeisLifetime.Scoped:insts[_type]=instreturninst
defis_registered(self,_type:type)->bool:"""Return True if ``_type`` has a registration. See ServiceProvider.is_registered."""return_typeinself._dependency_lookup
These describe a registration after it has been parsed. Application code rarely
touches them directly; they are public because factories and diagnostics can
read them.
defactivate(self,provider=None)->Any:""" Instantiate this service according to its lifetime and factory/constructor logic. """ifnotself.constructor_params:instance=self.implementation_type()else:kwargs={param.name:provider.resolve(param.dependency_type)forparaminself.constructor_params}instance=self.implementation_type(**kwargs)returninstance