di

class litestar.di.DIContext[source]

Bases: object

A live DI scope. Manages resolution and lifetime of dependencies

async __aenter__() → Self[source]

Open this context.

A context can only be entered once. Closing and re-entering it again is an error.

Raises:
  • DIContextClosedError – If this context, or its parent context, has already been closed

  • DIScopeError – If it has already been entered, or its parent has not been

async __aexit__(exc_type: type[BaseException] | None, exc: BaseException | None, traceback: TracebackType | None) → None[source]

Close this context and clean up all its dependencies

__init__(registry: DIRegistry, scope: str | None = None, parent: DIContext | None = None, seeds: Mapping[DependencyKey, Any] | None = None, prepared: PreparedDIContext | None = None) → None[source]

A DI context to resolve dependencies.

If scope is not given, the outermost scope is used, or, when parent is given, the scope immediately following the parent’s. Creating a context freezes registry.

Parameters:
  • registry – The registry to resolve through

  • scope – The scope this context owns

  • parent – The context before this

  • seeds – Values for the seed keys of this scope. If registry declares seeds, values for all seeds must be given

  • prepared – The PreparedDIContext of registry, scope and parent, which has checked them. If not given, it is created

enter_nested(registry: DIRegistry | None = None, scope: str | None = None, seeds: Mapping[DependencyKey, Any] | None = None) → DIContext[source]

A new DIContext, with this instance set as its parent.

async with app_context.enter_nested() as request_context:
    ...
Parameters:
  • registry – The registry the child resolves through. Defaults to this context’s

  • scope – The scope to enter. Defaults to the one immediately following this context’s

  • seeds – Values for the seed keys of the nested scope

get(key: str | TypeForm[Any]) → Any[source]

Return the previously solved value of key.

Raises:

DIResolutionError – If the key has not been resolved in this context or a parent

async inject(fn: Callable[..., Any], args: tuple[Any, ...] = (), kwargs: Mapping[str, Any] | None = None, *, sync_to_thread: bool | None = None) → Any[source]

Resolve all dependencies of fn, inject them into fn, and return its return value.

args and kwargs are passed to fn. When a parameter is declared a dependency but still passed explicitly, the explicit form will take precedence.

This method should not be used from within a dependency provider, as it can result in deadlocks: When solved dynamically, a dependency can request itself, creating a cycle, which can only be checked exhaustively if all dependencies are declared upfront. A best-effort check is performed to prevent calling this method from within a dependency, but it should not be relied on.

Parameters:
  • fn – A callable or an InjectionTarget

  • args – Positional arguments for fn

  • kwargs – Keyword arguments for fn

  • sync_to_thread – Whether a synchronous fn runs in a worker thread

Raises:
async solve(key: str | TypeForm[Any]) → Any[source]

Solve for key and return its value.

This method should not be used from within a dependency provider, as it can result in deadlocks: When solved dynamically, a dependency can request itself, creating a cycle, which can only be checked exhaustively if all dependencies are declared upfront. A best-effort check is performed to prevent calling this method from within a dependency, but it should not be relied on.

Raises:
async solve_arguments(fn: Callable[..., Any], *, supplied: Collection[str] = ()) → dict[str, Any][source]

Return the resolved dependencies of fn, keyed by parameter name.

Parameters in supplied and optional dependencies without a provider are left out.

Parameters:
  • fn – A callable or an InjectionTarget

  • supplied – Names of parameters not to be resolved

Raises:
  • MissingProviderError – If a required dependency has no provider.

  • DIResolutionError – If supplied names a parameter fn does not declare, unless fn takes **kwargs; or if the call is found to come from inside a factory, a best effort check to avoid misuse.

async solve_many(*keys: str | TypeForm[Any]) → tuple[Any, ...][source]

Solve all keys, and return their resolved values in the order of keys.

This method should not be used from within a dependency provider, as it can result in deadlocks: When solved dynamically, a dependency can request itself, creating a cycle, which can only be checked exhaustively if all dependencies are declared upfront. A best-effort check is performed to prevent calling this method from within a dependency, but it should not be relied on.

Raises:
class litestar.di.DIRegistry[source]

Bases: object

A registry of DI providers.

__init__(name: str, providers: Iterable[Provider], scopes: Iterable[str] | None = None) → None[source]

A registry of DI providers.

A registry holds every provider needed to satisfy the keys it declares.

A registry is mutable until the first time a graph is solved from it, creating a DIContext or calling predecessors_of(), at which point it freezes, validating the graph and disallowing further registrations.

Parameters:
  • name – Name of this registry. Only used for debugging purposes in error messages

  • providers – Providers available in this registry

  • scopes – Available scopes, in order, outermost first. Defaults to ("app", "request", "handler")

Raises:

DIRegistrationError – If the scopes or the providers are invalid.

check_target(target: Callable[..., Any]) → None[source]

Check that this registry has a provider for every required dependency of target.

Parameters:

target – A callable or an InjectionTarget

Raises:

MissingProviderError – If a required dependency of target has no provider

freeze() → None[source]

Freeze the registry and validate the dependency graph.

Subsequent calls to this method are a no-op.

Raises:
get_provider(key: DependencyKey) → Provider | None[source]

Return the provider for key, or None if no provider for key has been registered

predecessors_of(provider: Provider) → frozenset[Provider][source]

Return predecessors of provider as declared in this registry.

Raises:

DIRegistrationError – If this registry does not declare provider.

property providers: Mapping[DependencyKey, Provider]

The registry’s providers

register(provider: Provider, override: bool = False) → None[source]

Register a provider.

Parameters:
  • provider – The provider or callable to create a provider instance

  • override – If False, trying to register a provider for an already existing key raises DIRegistrationError

Raises:

DIRegistrationError – If the registry is frozen, the key is a duplicate and override is not set, the scope is unknown, or the provider cannot be inspected.

register_callable(fn: Callable[..., Any], key: DependencyKey, scope: str | None = None, sync_to_thread: bool | None = None, override: bool = False) → None[source]

Register a callable as a new provider.

fn will be wrapped in one Provider. The key type is inferred from key: A string will be a provider for a NamedDependency, anything else a TypeDependency.

Parameters:
  • fn – The factory callable to create a provider instance from

  • key – Key to register under

  • scope – Scope of the new provider

  • sync_to_thread – Whether a bare sync callable runs in a worker thread: see Provider

  • override – If False, trying to register a provider for an already existing key raises DIRegistrationError

Raises:

DIRegistrationError – If the registry is frozen, the key is a duplicate and override is not set, the scope is unknown, or the provider cannot be inspected.

class litestar.di.Dependency[source]

Bases: object

Mark a parameter as a dependency.

async def handler(
    session: Annotated[Session, Dependency("db_session")],
    replica: Annotated[Engine, Dependency(ReplicaEngine)],
) -> None: ...
key: DependencyKey | None

The key to resolve

kind: Literal['named', 'type'] | ProviderKind | None

Whether to resolve by name or by type. If not given, inferred from ‘key’, or by name without a key

__init__(key: DependencyKey | None = None, kind: Literal['named', 'type'] | ProviderKind | None = None) → None
class litestar.di.InjectionParameter[source]

Bases: object

A parameter of a provider or an injection target that DI fills.

parameter_name: str

Name of the parameter on the callable.

key: str | type[Any]

Key of the dependency

kind: ProviderKind

The provider kind

optional: bool

Whether the parameter is optional (i.e. has a default)

__init__(parameter_name: str, key: str | type[Any], kind: ProviderKind, optional: bool = False) → None
class litestar.di.InjectionTarget[source]

Bases: object

A callable whose dependencies are read from its signature, for DIContext.inject(), DIContext.solve_arguments() and DIRegistry.check_target().

It has the same calling semantics as a Provider, but does not provide a value into the context.

__call__(*args: Any, **kwargs: Any) → Any[source]

Call the callable as-is

__init__(fn: Callable[..., Any], signature: ParsedSignature | None = None) → None[source]

Wrap fn as an injection target.

Parameters:
  • fn – The callable to call with its dependencies resolved

  • signature – The parsed signature of fn, used instead of reading it from fn. For a functools.partial(), it may be that of the callable it wraps

property fn: Callable[..., Any]

The wrapped callable

class litestar.di.PreparedDIContext[source]

Bases: object

Factory to create a DIContext, from a given registry, scope, and parent context

__init__(registry: DIRegistry, scope: str | None = None, parent: DIContext | PreparedDIContext | None = None) → None[source]

Prepare contexts of registry at scope, nested in parent.

If scope is not given, the outermost scope is used, or, when parent is given, the scope immediately following the parent’s. Freezes registry.

Parameters:
  • registry – The registry the contexts resolve through

  • scope – The scope the contexts own

  • parent – The context before these, or its prepared context

Raises:
  • DIScopeError – If registry and the registry of parent declare different scopes, registry has no scope scope, or scope is not the one following the scope of parent, without a parent the outermost one

  • DIContextClosedError – If parent is a closed context

  • DIRegistrationError – If parent is a context and registry was created after the outermost context before it was entered

create(parent: DIContext | None = None, seeds: Mapping[DependencyKey, Any] | None = None) → DIContext[source]

Return a new DIContext of the registry at the scope.

Parameters:
  • parent – The context before the new one: a context of the registry and scope of the parent given to this prepared context, with the outermost context entered after the registry was created

  • seeds – Values for the seed keys of the scope. If the registry declares seeds, values for all seeds must be given

class litestar.di.Provide[source]

Bases: object

A dependency declaration, converted at handler registration to a Provider of dependency under the key it is declared with: scope "app" with use_cache=True, "handler" otherwise, and sync_to_thread as given.

__init__(dependency: AnyCallable | type[Any], use_cache: bool = False, sync_to_thread: bool | None = None) → None[source]

Store the arguments, warning that Provide is deprecated.

Parameters:
  • dependency – The factory callable

  • use_cache – Whether the provider has scope "app" instead of "handler"

  • sync_to_thread – Whether a sync callable runs in a worker thread

class litestar.di.Provider[source]

Bases: object

A factory to produce a value

__call__(*args: Any, **kwargs: Any) → Any[source]

Call underlying factory as-is

__init__(fn: Callable[..., Any] | None, kind: Literal['named', 'type'] | ProviderKind | None = None, scope: str = 'handler', key: DependencyKey | None = None, sync_to_thread: bool | None = None, signature: ParsedSignature | None = None) → None[source]

DI provider. A factory to produce a value.

A factory callable may be:

  • an async callable

  • a sync callable: In this case, sync_to_thread must be passed explicitly, to define how it should be invoked. Blocking synchronous callables should pass sync_to_thread=True, so they can run in a thread pool without blocking the main event loop. See Sync vs. Async for more info. A class is treated as a non-blocking sync callable. It’s __init__ and __new__ methods should never block

  • an async generator, yielding exactly once. The yielded value is the factory value. the code after the yield will be invoked as a cleanup step when this provider’s DIContext closes. If the context is closing with an active exception, that exception will be thrown into the generator. Cleanups are guaranteed to run in reverse order they providers were invoked in. Every cleanup will be invoked, even if prior cleanups raised an exception. Exceptions during cleanup steps are re-raised once all cleanups have completed.

  • a sync generator, yielding exactly once, with the cleanup step of an async generator. The code up to the yield runs in a worker thread, the cleanup step in a thread of its own, both in one contextvars.Context: a context variable set before the yield is set after it, and set for whoever resolves the provider. A context variable set where the context closes is set for the cleanup step

A provider may declare no ‘fn’, which makes it a seed. Seeds are expected to be given values for their context explicitly when that context is created. The shorthand for this is Provider.seed()

Parameters:
  • fn – The factory callable, or None to declare a seed, whose value is given to the context owning its scope when it is built

  • kind – Whether this provider is keyed by name or by type

  • scope – Name of the lifetime-scope where the produced value is stored

  • key – The key to register under. If omitted it is inferred: from fn.__name__ for a named provider, and from the return annotation (or the class itself) for a type provider

  • sync_to_thread – Whether a sync callable runs in a worker thread

  • signature – The parsed signature of fn, used instead of reading it from fn. For a functools.partial(), it may be that of the callable it wraps

Raises:

DIRegistrationError – If fn is not a supported callable, key contradicts kind, a seed is declared without a key or with a signature, or sync_to_thread contradicts the callable’s form.

property dependencies: tuple[InjectionParameter, ...]

Sub-dependencies of this provider

property is_seed: bool

Whether this provider is a seed

property key: str | type[Any]

Key this provider is registered under

property non_di_parameters: tuple[str, ...]

Names of the factory callable’s parameters that a functools.partial() binds by keyword

property request_parameters: tuple[RequestParameter, ...]

Sub-dependencies of this provider that carry a parameter or body marker

resolve_signature(signature: ParsedSignature | None = None) → None[source]

Extract sub-dependencies and the remaining parameters from the provider callable’s signature. signature is read instead of the callable’s when the provider was given none at construction.

classmethod seed(key: str | type[Any], scope: str = 'handler') → Provider[source]

Create a provider without a factory. Its value must be passed to the DIContext explicitly at creation time.

The kind is inferred from the key. A string key creates a name dependency, anything else a type dependency.

class litestar.di.ProviderKind[source]

Bases: StrEnum

Types of provider keys

__new__(value)
NAMED = 'named'

Keyed by a name

TYPE = 'type'

Keyed by a type

class litestar.di.RequestParameter[source]

Bases: object

Parameter of a Provider or InjectionTarget declared by a parameter marker, such as FromQuery[...], or a body marker, such as JSONBody[...]

parameter_name: str

Name of the parameter on the callable

param_type: ParamType | None

Type of the request parameter. None for the request body

name: str

Name of the request parameter in the request, as declared. Empty for the request body

field_definition: FieldDefinition

The parameter’s declaration. Its kwarg_definition is the marker

marker: ParameterKwarg | BodyKwarg

The parameter marker or body marker declaring the parameter

__init__(parameter_name: str, param_type: ParamType | None, name: str, field_definition: FieldDefinition, marker: ParameterKwarg | BodyKwarg) → None
property is_body: bool

Whether a body marker declares the parameter

property key: str

The dependency key, "<param type>:<name>" with a header’s name lower-cased, or "body:" for the request body

class litestar.di.ValueGraphDivergence[source]

Bases: object

Finding of check_divergence(): a node at which two registries’ value graphs diverge. provider, declared under key by both, has different predecessors in registry than in first_registry

bindings: Mapping[DependencyKey, tuple[Provider | None, Provider | None]]

bindings that differ, as (first, this) per key, None for an unbound optional dependency

__init__(key: DependencyKey, provider: Provider, first_registry: str, registry: str, bindings: Mapping[DependencyKey, tuple[Provider | None, Provider | None]]) → None
litestar.di.check_divergence(registries: Iterable[DIRegistry], *, scopes: Collection[str] | None = None, ignore: Iterable[DependencyKey | Provider] | None = None, raise_on_divergence: bool = False) → None[source]

Check for divergences in the predecessors of providers shared by registries.

Why does this matter? A provider registered in one or more registry that, through differing predecessors in each registry, will create unique values below the lifetimes of its scope.

@provide(scope="app", key="session")
async def create_session(engine: NamedDependency[Engine]) -> Session:
    with Session(bind=engine) as session:
        yield session

@provide(scope="app", key="engine")
async def engine_one() -> str:
    return create_engine(<some params>)

@provide(scope="app", key="engine")
async def engine_two() -> str:
    return create_engine(<some other params>)

alice = DIRegistry("alice", [create_session, engine_one])
bob = DIRegistry("bob", [create_session, engine_two])

app_ctx = DIContext(registry=DIRegistry(), scope="app")
alice_ctx = DIContext(alice, scope="request", parent=app_ctx)
bob_ctx = DIContext(alice, scope="request", parent=app_ctx)

await alice_ctx.solve("session")  # there is now an 'engine' and a 'session' in app_ctx
await bob_ctx.solve("session")  # a distinct 'engine' and a 'session' are created in app_ctx

In this example, both registries share the provider for the ‘session’ key, but have different providers for the ‘engine’ key. Since ‘session’ depends on ‘engine’, this is a divergence. When resolving ‘session’ through ‘alice_ctx’ , it must get a different ‘engine’ then when resolved through ‘bob_ctx’, which the context will solve by invoking ‘create_session’ again, even if a value for its key is already present in ‘app_ctx’.

Raises:

DivergenceError – If raise_on_divergence is set, at the first finding.

litestar.di.provide(scope: str = 'handler', kind: Literal['named', 'type'] | ProviderKind | None = None, key: DependencyKey | None = None, sync_to_thread: bool | None = None) → Callable[[Callable[..., Any]], Provider][source]

A decorator wrapping the callable into a Provider.

Parameters:
  • scope – Name of the scope owning the produced value.

  • kind – Whether the provider is keyed by name or by type. If not given, inferred from key, or by name without a key

  • key – Key this factory provides for. If not given, will be inferred. From the callable’s name for kind="named" (the default), and from the callable’s return type for kind="type"

  • sync_to_thread – Whether a sync callable runs in a worker thread; see Provider for more information

Raises:

DIRegistrationError – If used as a bare @provide without parentheses.

litestar.di.NamedDependency

Mark a parameter as a dependency resolved by name.

Equivalent to Annotated[T, Dependency(kind="named")]

litestar.di.TypeDependency

Mark a parameter as a dependency resolved by type.

Equivalent to Annotated[T, Dependency(kind="type")]

litestar.di.DependencyKey = str | type[Any]
exception litestar.di.exceptions.CaptiveDependencyError[source]

Bases: DIGraphError

A provider depends on a value from a later scope, which it would keep using after that value was cleaned up

exception litestar.di.exceptions.CircularDependencyError[source]

Bases: DIGraphError

exception litestar.di.exceptions.DIContextClosedError[source]

Bases: DIResolutionError

A DIContext was used after it was closed.

exception litestar.di.exceptions.DIException[source]

Bases: LitestarException

exception litestar.di.exceptions.DIGraphError[source]

Bases: DIException

exception litestar.di.exceptions.DIRegistrationError[source]

Bases: DIException

exception litestar.di.exceptions.DIResolutionError[source]

Bases: DIException

exception litestar.di.exceptions.DIScopeError[source]

Bases: DIResolutionError

A scope was entered out of order, skipped, repeated, not at all, does not exist

exception litestar.di.exceptions.DivergenceError[source]

Bases: DIGraphError

Covering a ValueGraphDivergence

exception litestar.di.exceptions.DivergenceWarning[source]

Bases: LitestarWarning

Covering a ValueGraphDivergence

exception litestar.di.exceptions.MissingProviderError[source]

Bases: DIGraphError

A dependency has no provider registered in the registry

exception litestar.di.exceptions.MissingSeedError[source]

Bases: DIResolutionError

A context was built without a value for a seed key its registry declares at its scope

exception litestar.di.exceptions.ScopeMismatchError[source]

Bases: DIResolutionError

A provider exists, but its scope is not entered by the requesting context or any context above it