Skip to main content

Module di

Module di 

Source
Expand description

Dependency injection (Depends), inspired by FastAPI.

A Dependency is any type that knows how to build itself from the request (Dependency::resolve). Handlers ask for one with Depends<T>; dependencies may in turn depend on others through ResolveContext::resolve.

§Scoping and caching

Resolution is request-scoped and cached: within one request the same T is resolved at most once, no matter how many handler arguments or other dependencies ask for it. Failed resolutions are not cached.

§Application-scoped values, overrides and global dependencies

  • App::provide registers a shared value. It takes precedence over T::resolve for Depends<T> (when T: Dependency) and is the only way to inject types that are not dependencies, via Provided<T>.
  • App::override_dependency / App::override_value replace T::resolve (also when T is requested by another dependency); meant for tests.
  • App::dependency runs a dependency before every routed request of the app and its mounts and short-circuits with its error (e.g. 401). Unrouted requests (404) and the generated documentation endpoints are not affected. Per-route dependencies are not provided; add a Depends<T> argument to the handler instead.

A mounted child app sees its parent’s registrations; its own registrations take precedence inside the child.

§Teardown

Drop cannot be async, so cleanup that must await is registered with ResolveContext::on_teardown (the analogue of FastAPI’s yield). Teardown futures run after the response has been produced, in reverse (LIFO) registration order, on a spawned task; errors and panics are logged. Teardown is best-effort and not tied to the end of response streaming: a streaming body may still be sent while teardown runs.

§Documentation

Dependency::describe contributes OpenAPI parameters; Depends<T> forwards to it, so headers/queries of nested dependencies show up in the operation (cycles are guarded).

Structs§

Depends
Extractor injecting a Dependency (request-scoped, cached).
Provided
Extractor for a value registered with App::provide (any Send + Sync + 'static type, not only dependencies).
RequestHead
Owned snapshot of the request head handed to dependency overrides.
ResolveContext
Passed to Dependency::resolve: request access plus nested resolution.

Enums§

DependencyError
Failure inside the dependency machinery. Rendered to clients as an opaque 500; the details are logged.

Traits§

Dependency
A type that can be built from a request and injected with Depends.
TeardownOutput
What a teardown future may return: () or a Result<(), E> whose error is logged.