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::provideregisters a shared value. It takes precedence overT::resolveforDepends<T>(whenT: Dependency) and is the only way to inject types that are not dependencies, viaProvided<T>.App::override_dependency/App::override_valuereplaceT::resolve(also whenTis requested by another dependency); meant for tests.App::dependencyruns 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 aDepends<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(anySend + Sync + 'statictype, not only dependencies). - Request
Head - Owned snapshot of the request head handed to dependency overrides.
- Resolve
Context - Passed to
Dependency::resolve: request access plus nested resolution.
Enums§
- Dependency
Error - 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. - Teardown
Output - What a teardown future may return:
()or aResult<(), E>whose error is logged.