IoC Container & Dependency Injection
API reference for ZCore's Inversion of Control container, lifecycle registration methods, type unwrapping, and Inject type marker.
The IoCContainer manages class instantiation and lifecycles across your application. It handles registration, keyword-based constructor auto-wiring via cached reflection signatures, union type unwrapping, and circular dependency detection across Singleton, Scoped, and Transient lifecycles.
Class Definition
from zcore.kernel.di import IoCContainer
class IoCContainer:
def __init__(self) -> None:
...Global Instance
ZCore exposes a pre-initialized global container instance used throughout the framework:
from zcore import container
# or: from zcore.kernel.di import containerRegistration & Inspection Methods
is_registered
Checks whether an interface or class is actively registered across any container lifecycle store (_singletons, _scoped_definitions, _factories), active request scopes (_scoped_instances), or represents AsyncSession. Automatically unwraps union and annotated types before verification.
def is_registered(self, interface: type[Any]) -> bool: ...Prop
Type
_unwrap_type
A static utility that recursively unwraps Annotated, typing.Union, and Python 3.10+ union types (types.UnionType, such as IService | None = None) to locate the underlying concrete dependency type.
@staticmethod
def _unwrap_type(annotation: Any) -> Any: ...register_singleton
Registers a pre-constructed instance as a shared global singleton.
def register_singleton(self, interface: type[Any], instance: Any) -> None: ...Prop
Type
register_scoped
Registers a class bound to a request-scoped lifecycle. The class is instantiated once per context scope (scope_id) and cached across the dependency graph for the duration of that request.
def register_scoped(self, interface: type[Any], implementation: type[Any]) -> None: ...Prop
Type
register_scoped_instance
Registers a pre-constructed instance directly into the active request scope store.
def register_scoped_instance(self, interface: type[Any], instance: Any) -> None: ...Prop
Type
Raises DIException if invoked outside of an active request scope boundary.
register_transient
Registers a class bound to a transient lifecycle. A fresh instance is constructed on every resolution call.
def register_transient(self, interface: type[Any], implementation: type[Any]) -> None: ...Prop
Type
Resolution & Scope Management
resolve
Dynamically evaluates registered bindings (Singleton, Scoped, Transient) or executes keyword-based constructor auto-wiring to assemble the dependency tree.
def resolve(
self,
interface: type[T],
_stack: set[type[Any]] | None = None
) -> T: ...Prop
Type
Scope Boundary Enforcement:
Attempting to resolve a scoped dependency or AsyncSession outside of an active scope context (when _current_scope_id is None) immediately raises DIException:
DIException: Cannot resolve scoped dependency 'TaskService' outside of an active scope.Constructor Auto-Wiring & _DependencySignature Caching:
When auto-wiring class constructors:
- Keyword Injection (
**kwargs): Dependencies are assembled into a keyword dictionary and injected viatarget_class(**resolved_kwargs), preventing argument misplacement. - Default Parameter Bypass: Parameters declaring default values (
param.default is not empty) that are not explicitly registered in the container (such as primitiveint,str, or unregistered optional types) are skipped, allowing Python to safely apply their declared defaults. - Signature Cache: Evaluated parameter-to-dependency mappings are stored in
_dependency_signature_cacheas list-compatible_DependencySignatureinstances, bypassing reflection overhead on subsequent resolutions.
clear_scope
Explicit scope cleanup hook called during middleware teardown to purge request-scoped instances.
def clear_scope(self, scope_id: str | None = None) -> None: ...FastAPI Integration Helpers
Inject[T]
Dynamic type marker bridging FastAPI route parameters with the IoC container via Annotated:
from zcore import Inject
@router.get("/dashboard")
async def get_dashboard(service: Inject[DashboardService]):
return await service.get_data()Injector
Callable wrapper class converting a type interface lookup into a FastAPI Depends resolver.
Background Task & Scope Helpers
background_scope
Asynchronous context manager providing an isolated IoC container scope, a dedicated AsyncSession database session, and ZContext variable storage for background execution independent of the originating HTTP request lifecycle.
from zcore import background_scope
async def process_report():
async with background_scope(inherit_context=True):
...Prop
Type
background_task
Decorator that wraps a background task with an isolated background_scope and automatically resolves any unprovided type-annotated parameters from the IoC container using _unwrap_type. Supports both asynchronous coroutines and synchronous functions (executed in a worker threadpool).
import uuid
from zcore import background_task
from tasks.services import TaskService
@background_task
async def send_welcome_email(user_id: uuid.UUID, email_service: TaskService):
await email_service.notify(user_id)Passing an active request AsyncSession directly as an argument to background tasks is discouraged. Let @background_task automatically inject a dedicated, isolated session.
Exceptions
CircularDependencyError
Raised when a cyclic resolution loop is detected during dependency auto-wiring (e.g., ServiceA -> ServiceB -> ServiceA). Inherits from DIException.
DIException
Base exception class for all container-level dependency injection runtime errors.
Exceptions & Centralized Error Handling
API reference for ZCore's domain exception hierarchy, HTTP status code mappings, sanitization helpers, and unified handler registration.
Inject & Injector
API reference for the dynamic Annotated type marker bridging FastAPI route parameters with the IoC container.