ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Core Concepts

Providers and injection

ProvidersTraits and qualifiersCollections and optional dependenciesScopes

Modules

ModulesConfigured modulesDynamic and lazy modules

Running the application

Application phasesLifecycle hooksShutdownStandalone executions

Diagnostics and the value API

The wiring reportWithout macros

Protocols

Integrations

Operating

Reference

Core Concepts

Traits and qualifiers

Binding a provider under a trait, and telling two instances of one type apart with a qualifier.

A provider bound under a trait is injected as Dep<dyn Trait>, and the consumer never names the type behind it. Two instances of one type, a primary and a replica database, are told apart by a qualifier type.

This page follows examples/03-traits-and-qualifiers.

Binding under a trait

PgUserRepo as dyn UserRepo in a providers list binds the provider under the trait. Consumers read Dep<dyn UserRepo>.

/// A trait a provider is bound under. `Send + Sync` is what `Dep<dyn UserRepo>` requires.
pub trait UserRepo: Send + Sync {
    fn name(&self) -> &'static str;
}

#[injectable]
pub struct PgUserRepo;

impl UserRepo for PgUserRepo {
    fn name(&self) -> &'static str {
        "pg"
    }
}

#[module(
    imports = [DbModule],
    providers = [PgUserRepo as dyn UserRepo],
    controllers = [UserController],
)]
pub struct AppModule;

as dyn UserRepo leaves the concrete key bound beside the trait key, so Dep<PgUserRepo> also resolves, to the same instance. The test checks the pointers:

let repo: Dep<dyn UserRepo> = server.handle.get().await.unwrap();
let concrete: Dep<PgUserRepo> = server.handle.get().await.unwrap();
assert!(std::ptr::addr_eq(std::sync::Arc::as_ptr(concrete.arc()), std::sync::Arc::as_ptr(repo.arc())));

The key is the exact type. dyn Repo and dyn Repo + Send + Sync are different keys. A binding under one and a read of the other compiles on both sides and fails at wire() as a missing dependency whose help line names both spellings. The fix is to put Send + Sync on the trait as supertraits and write dyn Repo everywhere.

Qualifiers

A qualifier is any 'static type, usually a unit struct. Dep<Db, Primary> reads the key Db @ Primary.

/// Two instances of one type, told apart by a qualifier: any `'static` type will do.
pub struct Primary;
pub struct Replica;

pub struct Db(pub &'static str);

#[module(
    providers = [Db("primary") @ Primary, Db("replica") @ Replica],
    exports = [Db @ Primary, Db @ Replica],
)]
pub struct DbModule;

#[controller]
pub struct UserController {
    repo: Dep<dyn UserRepo>,
    primary: Dep<Db, Primary>,
    replica: Dep<Db, Replica>,
}

The @ is the same spelling reports print for a key. In providers it follows a type or a value: PgUserRepo @ Primary, Db("replica") @ Replica. When both a trait and a qualifier are written, PgUserRepo as dyn UserRepo @ Primary binds PgUserRepo @ Primary and dyn UserRepo @ Primary, and leaves the unqualified keys unbound.

An export leaves a module by key. Db alone means Db @ (), so the exports above name both qualified keys.

A closure binding and an into contribution take no @. A binding like that, such as a qualified closure or a qualified readiness check, is written against the value API with .qualified::<Q>().

Reading the wrong key

The unqualified Dep<Db> is a different key from Db @ Primary. A consumer that reads it, with only qualified Db bindings in sight, fails wire():

#[controller]
struct Unqualified {
    _db: Dep<Db>,
}

#[handlers]
impl Unqualified {
    #[ulo_http::get("/")]
    fn read(&self) -> &'static str {
        "never"
    }
}

#[module(imports = [DbModule], controllers = [Unqualified])]
struct UnqualifiedModule;

let Err(StartupError::Wiring(errors)) = App::builder(UnqualifiedModule).wire() else {
    panic!("wiring should fail");
};
let [WiringError::Missing { key, consumer, module, .. }] = errors.iter().collect::<Vec<_>>()[..] else {
    panic!("expected one missing dependency, got {errors}");
};
assert_eq!(key.to_string(), "Db");
assert_eq!(consumer, "Unqualified (field `_db`)");
assert_eq!(module.to_string(), "UnqualifiedModule");

Aliases

An alias gives a second qualifier to a binding that already exists, with no second instance. It is a value-API call, m.alias::<Db, ReadOnly>().of::<Primary>(): Db @ ReadOnly reads the Db @ Primary binding. It is exercised in crates/ulo/tests/bindings.rs. An alias that points at a key nothing visible binds is reported by wire().

Running the example

cargo run -p ex-03-traits-and-qualifiers

GET /repo answers pg, GET /write answers primary, and GET /read answers replica.

Providers

Declaring a provider, injecting it with Dep, and what happens when its constructor fails.

Collections and optional dependencies

Many<dyn T> gathers every contribution to a key, and Option<Dep<T>> reads what may not be bound.

On this page

Binding under a traitQualifiersReading the wrong keyAliasesRunning the example