Skip to content

Integration base

depi.integration is the contract every framework adapter is built on. It lives in core and stays dependency-free. You only need this page if you are writing a new adapter; for using the existing ones see Integrations.

An adapter subclasses BaseInjector and implements setup(app) to open a ServiceScope per request, bind it with set_current_scope, and dispose it when the request ends.

BaseInjector

BaseInjector(provider: ServiceProvider, param_name: str = 'provider', autowire: bool = False)

Bases: ABC

Base class for framework integrations.

Parameters:

  • provider (ServiceProvider) –

    the built ServiceProvider to resolve from.

  • param_name (str, default: 'provider' ) –

    the keyword argument the request scope is passed as in the default (non-autowire) mode. Name it to taste -- container is a common alternative.

  • autowire (bool, default: False ) –

    when True, inject resolves registered types by annotation instead of passing the scope. Not supported by every integration; FastAPI rejects it outright.

Source code in packages/depi-core/depi/integration.py
def __init__(
    self,
    provider: 'ServiceProvider',
    param_name: str = 'provider',
    autowire: bool = False
):
    """
    Args:
        provider: the built ServiceProvider to resolve from.
        param_name: the keyword argument the request scope is passed as in
            the default (non-autowire) mode. Name it to taste -- ``container``
            is a common alternative.
        autowire: when True, ``inject`` resolves registered types by
            annotation instead of passing the scope. Not supported by every
            integration; FastAPI rejects it outright.
    """
    self._provider = provider
    self._param_name = param_name
    self._autowire = autowire

provider property

provider: ServiceProvider

The provider this injector resolves from.

create_scope

create_scope() -> ServiceScope

Create a new, unbound dependency scope.

Source code in packages/depi-core/depi/integration.py
def create_scope(self) -> 'ServiceScope':
    """Create a new, unbound dependency scope."""
    return self._provider.create_scope()

current_scope

current_scope() -> ServiceScope

Return the scope bound to the current request context.

Raises:

Source code in packages/depi-core/depi/integration.py
def current_scope(self) -> 'ServiceScope':
    """
    Return the scope bound to the current request context.

    Raises:
        NoActiveScopeError: if setup(app) never ran, or this is called
            outside a request.
    """
    return current_scope()

setup abstractmethod

setup(app) -> None

Install per-request scope management onto app.

Source code in packages/depi-core/depi/integration.py
@abstractmethod
def setup(self, app) -> None:
    """Install per-request scope management onto ``app``."""

inject

inject(fn: Callable) -> Callable

Decorator handing the request scope to fn.

Default mode passes the scope as the param_name keyword argument. With autowire=True, parameters annotated with registered types are resolved and passed individually instead.

Uses functools.wraps, so it composes inside a decorator stack (route registration, auth, response handling) without losing the wrapped function's identity.

Source code in packages/depi-core/depi/integration.py
def inject(self, fn: Callable) -> Callable:
    """
    Decorator handing the request scope to ``fn``.

    Default mode passes the scope as the ``param_name`` keyword argument.
    With ``autowire=True``, parameters annotated with registered types are
    resolved and passed individually instead.

    Uses functools.wraps, so it composes inside a decorator stack (route
    registration, auth, response handling) without losing the wrapped
    function's identity.
    """
    return self._make_inject_wrapper(fn)

injectable_parameters

injectable_parameters(fn: Callable, provider: ServiceProvider) -> Dict[str, type]

Map parameter name -> registered type for the parameters depi should supply.

Parameters the provider does not know about are left alone, because the web framework almost certainly owns them (URL converters, query arguments). That is why autowire cannot fail fast on an unresolvable annotation: from here, "unregistered" and "supplied by the framework" look identical.

Called once at decoration time, never per request.

Source code in packages/depi-core/depi/integration.py
def injectable_parameters(
    fn: Callable,
    provider: 'ServiceProvider'
) -> Dict[str, type]:
    """
    Map parameter name -> registered type for the parameters depi should supply.

    Parameters the provider does not know about are left alone, because the web
    framework almost certainly owns them (URL converters, query arguments). That
    is why autowire cannot fail fast on an unresolvable annotation: from here,
    "unregistered" and "supplied by the framework" look identical.

    Called once at decoration time, never per request.
    """
    try:
        parameters = get_signature(fn).parameters
    except Exception:
        # Deliberately broad. Signatures are evaluated with eval_str=True, and
        # under `from __future__ import annotations` every annotation is a
        # string, so this can fail in many ways: an unimportable forward
        # reference (NameError), a malformed one (SyntaxError), a dotted name
        # whose attribute is missing (AttributeError), a builtin with no
        # retrievable signature (ValueError).
        #
        # None of those are depi's to diagnose, and all of them happen at
        # decoration time -- at import, before the app can even start. Claiming
        # nothing lets the framework supply the parameter and report the real
        # problem itself.
        return {}

    injectable = {}
    for name, param in parameters.items():
        if param.kind in _VARIADIC:
            continue
        annotation = param.annotation
        if annotation is inspect.Parameter.empty:
            continue
        if isinstance(annotation, type) and provider.is_registered(annotation):
            injectable[name] = annotation
    return injectable