IoC Container & Dependency Injection
API reference for ZCore's Inversion of Control container, lifecycle registration methods, and Inject type marker.
The IoCContainer manages class instantiation and lifecycles across your application. It handles registration, constructor auto-wiring via cached reflection signatures, 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 Methods
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 constructor auto-wiring to assemble the dependency tree.
def resolve(
self,
interface: Type[T],
_stack: Optional[Set[Type[Any]]] = None
) -> T: ...Prop
Type
Constructor Reflection & Signature Caching: If a type is not explicitly registered, resolve analyzes its __init__ constructor parameters. Evaluated dependencies are cached in _dependency_signature_cache to eliminate 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. Supports both asynchronous coroutines and synchronous functions (executed in a worker threadpool).
from zcore import background_task
from zcore.db.setup import SessionDep
@background_task
async def send_welcome_email(user_id: uuid.UUID, email_service: EmailService):
await email_service.send(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.