Scopes
How long an instance lives, and what the container refuses when scopes conflict.
A scope sets when a new instance is built and who shares it. There are three, plus the default, Auto.
| Scope | Declared | Lifetime |
|---|---|---|
singleton | #[injectable(singleton)] | One instance for the application, built during connect(). |
execution | #[injectable(execution)] | One instance per execution, shared by everything in that execution. |
transient | #[injectable(transient)] | A fresh instance at every injection point. |
Auto | #[injectable] or #[controller] | A provider is a singleton. A controller or enhancer (a guard, interceptor or error handler; see request lifecycle) is a singleton, or per-execution when anything below it needs an execution. |
An execution is one HTTP request, one WebSocket message, one RPC or gRPC call, or one standalone execution.
This page follows examples/05-scopes.
The scopes side by side
The example numbers every instance from one counter, and each request reads every scope twice, through two services, so the response shows which reads reached the same instance.
#[injectable(singleton)]
impl Shared {
fn new(ids: Dep<Ids>) -> Self {
Shared(ids.next.fetch_add(1, Ordering::SeqCst) + 1)
}
}
#[injectable(execution)]
impl PerCall {
fn new(ids: Dep<Ids>) -> Self {
PerCall(ids.next.fetch_add(1, Ordering::SeqCst) + 1)
}
}
#[injectable(transient)]
impl Fresh {
fn new(ids: Dep<Ids>) -> Self {
Fresh(ids.next.fetch_add(1, Ordering::SeqCst) + 1)
}
}
/// No scope written: a provider is a singleton.
#[injectable]
impl Defaulted {
fn new(ids: Dep<Ids>) -> Self {
Defaulted(ids.next.fetch_add(1, Ordering::SeqCst) + 1)
}
}First and Second are both #[injectable(execution)] and each reads all four. The controller reads First and Second:
/// Reads an execution-scoped dependency, so `Auto` makes the controller per-execution too.
#[controller]
pub struct ScopesController {
first: Dep<First>,
second: Dep<Second>,
}What the test asserts about the response:
singletonand the unmarkedAutoprovider: both reads see one instance, and the next request sees the same one. The two providers have different instances.execution: both reads inside a request see one instance, and each request gets its own.transient: the two reads in one request differ, and so do the reads of the next request.
A singleton can be read from outside a request with the same type, server.handle.get::<Shared>(), and it is the instance the requests read.
Inferring a controller's scope
A controller written with a bare #[controller], or an enhancer written with a bare #[injectable], is a singleton when nothing below it needs an execution, and per-execution otherwise. ScopesController reads Dep<First>, which is execution-scoped, so the container builds the controller once per call. Writing #[controller(singleton)] on a controller opts out of the inference, and a controller declared that way which needs execution data is refused.
A binding needs an execution when one of its injection points is Ext<T> (a value written into the execution's extension bag, see Standalone executions), ExecutionRef (a handle to the running execution), an execution input (a value a transport seeds into each execution, such as the HTTP request head; see The wiring report), or a dependency that needs one. Transients and Auto bindings pass the need upward.
A closure binding is inferred from what its parameters read, not from what its body does. || RequestTimer::start() reads nothing, so Auto builds it once and every call shares the timer. A closure that creates per-call state and reads nothing writes with(execution) = ...
What is refused
A scope conflict is found at wire(), with the dependency path that introduces it.
#[injectable(singleton)]
struct Pinned {
_per_call: Dep<PerCall>,
}
#[module(providers = [Ids, PerCall, Pinned])]
struct PinnedModule;
let Err(StartupError::Wiring(errors)) = App::builder(PinnedModule).wire() else {
panic!("wiring should fail");
};
let [WiringError::ScopeViolation { binding, declared, by_closure, controller, module, path }] =
errors.iter().collect::<Vec<_>>()[..]
else {
panic!("expected one scope violation, got {errors}");
};
assert_eq!(binding.to_string(), "Pinned");
assert_eq!(*declared, ScopeKind::Singleton);
assert!(!by_closure);
assert!(!controller);
assert_eq!(module.to_string(), "PinnedModule");
assert_eq!(path.join(" -> "), "Pinned -> PerCall (execution)");The printed form of that error is:
× scope violation: singleton `Pinned` in PinnedModule depends on per-execution data
└─ Pinned → PerCall (execution)
help: declare Pinned #[injectable(execution)], or inject a factory| Mistake | Found | Reported as |
|---|---|---|
| An explicit singleton reads execution data, through transients too | wire() | ScopeViolation, with the path. For a closure binding, ClosureScopeViolation. |
An Auto provider reads execution data | wire() | ScopeViolation; the help names #[injectable(execution)], or with(execution) for a closure. |
A controller declared singleton reads execution data | wire() | ScopeViolation with controller set. The help leads with "remove singleton", since an Auto controller is built per call when it needs to be, and names #[controller(execution)] second. |
A hook on an Auto type that inference made per-execution | wire() | HooksOnPerExecution |
A hook, readiness check, module hook or metadata closure reads Ext, ExecutionRef, an input or a per-execution key | wire() | ClosureNeedsExecution: nothing can satisfy the read where the closure runs. |
Ext<T> or ExecutionRef in a type declared singleton | compile | The AllowedIn bound: E0277, a `ulo::scope::Singleton` type cannot read `Ext<CurrentUser>` for that example, with the note to declare the type #[injectable(execution)] or #[injectable(transient)]. |
A lifecycle hook on a type declared execution or transient | compile | "lifecycle hooks are only allowed on singletons". |
The two compile-time refusals have trybuild fixtures in crates/ulo-codegen-tests/tests/ui: hook_on_execution_type, hook_on_transient_type and ext_in_an_explicit_singleton.
A refusal does not cascade. A singleton that needs an execution is refused once and stays a singleton for its readers, so one mistake yields one error.
Hooks run on singletons only. Execution-scoped and transient instances do not exist at startup or shutdown, so there is nothing to run a hook on. See Lifecycle hooks.
Running the example
cargo run -p ex-05-scopesGET / answers one line in the form singleton=a/b execution=c/d transient=e/f auto=g/h: each scope's instance id as First read it, then as Second did.