Service Container
Introduction
Most applications have values they build once and use everywhere: a client for your payment provider, a calculator that knows your tax rates, or a cache of settings loaded from the database. Building one in every handler is wasteful, and passing it through every function is tedious. The service container holds values like these. You register a service once, dust-framework builds it the first time something needs it, and every handler that asks for it by type gets the same instance.
Many Rust frameworks keep shared values in a single application state struct, such as Axum's State, which every handler receives whole. dust-framework registers each service on its own instead. A handler asks for just the services it uses, such as Inject<Stripe>, and a service that nothing asks for is never built.
A handler that takes Inject<Stripe> doesn't need to know where the API key comes from or how the client is built. And in tests, you may swap the service for a fake without changing the handler.
dust-framework registers its own services, such as the database, the cache, and the mailer, and you reach them through helpers such as dust::mail::to(..). You'll use the container for the services your application adds.
Reserve the container for types that hold configuration, external clients, shared state, or a trait contract you want to swap in tests. Stateless domain logic, such as placing an order or building an export, doesn't need an empty struct registered as a singleton. Write plain pub async fn functions in a module such as src/orders.rs instead, and call your models, helpers such as dust::mail::to(..), or dust::resolve directly from them.
These are the ways to register a service, and when each one fits:
| Registration | Builds the service | Suits |
|---|---|---|
singleton |
Once, on first use | A client or shared state that is the same for every request. |
instance |
Never; you pass the finished value | A value you can build at startup without I/O. |
bind |
Every time it is asked for | A service that reads the current request, such as the tenant. |
singleton_as, bind_as, instance_as |
As above, under a trait | A contract you may implement more than once. |
Every registration replaces an earlier one for the same type, which is how a package's service can be swapped in a test or an application. The container never binds a struct's traits on its own: registering Mapbox does not make Inject<dyn Geocoder> work until you register the contract too.
Registering services
Say your application charges cards through Stripe. The client needs your Stripe key, which a configuration section reads from the environment. This file defines the client and its configuration section:
// src/services/stripe.rsuse dust::config::Section;use dust::http::client;#[derive(Clone, Section)]pub struct StripeConfig { #[env("STRIPE_KEY", required)] pub key: String,}pub struct Stripe { key: String,}impl Stripe { pub fn new(key: &str) -> Self { Self { key: key.to_owned() } } pub async fn charge(&self, cents: u64) -> dust::Result<()> { client::post("https://api.stripe.com/v1/payment_intents") .token(&self.key) .form([("amount", cents.to_string()), ("currency", "usd".to_owned())]) .await?; Ok(()) }}Registering services in src/app.rs
Register the service in src/app.rs with with_services. singleton registers an async factory that runs the first time something asks for the service:
// src/app.rsuse dust::Application;use dust::foundation::ApplicationBuilder;use crate::services::stripe::{Stripe, StripeConfig};pub fn configure() -> ApplicationBuilder { Application::configure().with_services(|app| { app.singleton(async |app| { let key = &app.config().section::<StripeConfig>().key; Ok(Stripe::new(key)) }); })}Any handler can now take an Inject<Stripe>. The factory receives the container, so it may read your configuration with app.config(). It returns a dust::Result, so you may use ?. If it fails, the code that asked gets the error, and the next request tries again.
When a service needs nothing from your configuration or other services, you may build it yourself and register the finished value with instance. This Pricing calculator only needs your tax rate:
// src/app.rsuse crate::services::pricing::Pricing;app.instance(Pricing::new(0.07));Handlers then take Inject<Pricing>, the same as for a service built by a factory. To build a new service every time something asks for it, use bind, as Building a fresh service each time describes.
[!NOTE] Register the service itself, such as
Stripe, rather than anArc<Stripe>. The container already shares one instance, andInject<Stripe>looks for it underStripe. KeepArc<T>for the fields of services that depend on other services.
Building a fresh service each time
singleton builds one service and shares it with every request, which suits a payment client or anything else that works the same for every request. When a service needs something from the current request, such as the tenant or the logged-in user, register it with bind instead. Its factory runs every time something asks for the service, inside the request that asks, so it may read that request's context values. This TenantReports service is built for the tenant the current request belongs to:
// src/app.rsuse dust::context;use crate::services::reports::TenantReports;app.bind(async |_app| { let tenant: Option<String> = context::get("tenant"); Ok(TenantReports::new(tenant))});For a trait contract, use bind_as. To register a fresh-each-time service next to its code instead of in src/app.rs, use the #[bind] attribute.
Depending on other services
Services often need other services. A checkout, for example, needs Stripe to take payments. Keep the other service in an Arc<T> field:
// src/services/checkout.rsuse std::sync::Arc;use crate::services::stripe::Stripe;pub struct Checkout { stripe: Arc<Stripe>,}impl Checkout { pub fn new(stripe: Arc<Stripe>) -> Self { Self { stripe } } pub async fn pay(&self, cents: u64) -> dust::Result<()> { self.stripe.charge(cents).await }}In the factory, resolve the other service from the container. resolve returns it as an Arc<T>, ready to keep in a field:
// src/app.rsapp.singleton(async |app| { let stripe = app.resolve::<Stripe>().await?; Ok(Checkout::new(stripe))});Checkout shares the same Stripe as every handler that takes Inject<Stripe>.
Trait contracts
Sometimes you'd like code to use a service without naming its implementation. Say your application looks up addresses through a geocoder. It uses Mapbox today, but you might move to Google Maps later. Register the geocoder under a trait contract, and your handlers ask for Inject<dyn Geocoder>. Switching to Google Maps then changes one registration and no handlers.
Rust can't call async fn trait methods through dyn Trait, so add the async-trait crate to your Cargo.toml and put #[async_trait] on the trait and on each implementation:
[dependencies]async-trait = "0.1"Define the contract:
// src/services/geocoder.rsuse async_trait::async_trait;pub struct Coordinates { pub latitude: f64, pub longitude: f64,}#[async_trait]pub trait Geocoder: Send + Sync { async fn locate(&self, address: &str) -> dust::Result<Coordinates>;}Then implement it for Mapbox:
// src/services/mapbox.rsuse async_trait::async_trait;use dust::config::Section;use crate::services::geocoder::{Coordinates, Geocoder};#[derive(Clone, Section)]pub struct MapboxConfig { #[env("MAPBOX_TOKEN", required)] pub token: String,}pub struct Mapbox { token: String,}impl Mapbox { pub fn new(token: &str) -> Self { Self { token: token.to_owned() } }}#[async_trait]impl Geocoder for Mapbox { async fn locate(&self, address: &str) -> dust::Result<Coordinates> { // Fetch the address's coordinates from Mapbox's API... }}Register it with singleton_as, whose factory returns the service as an Arc<dyn Geocoder>:
// src/app.rsuse std::sync::Arc;use crate::services::geocoder::Geocoder;use crate::services::mapbox::{Mapbox, MapboxConfig};app.singleton_as(async |app| { let token = &app.config().section::<MapboxConfig>().token; Ok(Arc::new(Mapbox::new(token)) as Arc<dyn Geocoder>)});Now your handlers can ask for the contract instead of Mapbox itself. This one looks up an address without knowing which service answers:
use dust::prelude::*;use crate::services::geocoder::Geocoder;pub async fn show(geocoder: Inject<dyn Geocoder>) -> dust::Result<String> { let place = geocoder.locate("1600 Pennsylvania Ave NW, Washington, DC").await?; Ok(format!("{}, {}", place.latitude, place.longitude))}To move to Google Maps, implement Geocoder for a GoogleMaps service and change the registration. The handlers stay as they are. If you also register Mapbox itself, register the contract separately: the container never binds a struct's traits on its own. For a value you've already built, use instance_as.
Contracts make your tests simpler too. In a test, you may swap in a fake geocoder that returns fixed coordinates, so your tests never call Mapbox, and Mapbox needs no test-only code of its own. The testing guide's swapping services section shows how, with swap_as.
Replacing a service
Registering the same type again replaces the earlier registration. Your application's services register after every package's, so you may replace a package's service, such as a Stripe client from a billing package, with your own:
// src/app.rsApplication::configure().with_services(|app| { app.instance(Stripe::new("sk_test_..."));})Registering services with attributes
Each service you register in src/app.rs adds another factory to that file, so it can get long. The #[singleton] and #[bind] attributes let you register a service next to its code instead. Mark an async function with #[singleton], and it becomes the factory for the service it returns. The function takes what the service needs as arguments, the same way a handler does: configuration sections as Section<T>, and other services as Inject<T>.
This function registers the same Stripe service, from src/services/stripe.rs:
// src/services/stripe.rsuse dust::container::singleton;#[singleton]async fn stripe(config: Section<StripeConfig>) -> dust::Result<Stripe> { Ok(Stripe::new(&config.key))}To build a fresh service each time something asks for it, use #[bind] instead:
// src/services/reports.rsuse dust::container::bind;#[bind]async fn tenant_reports() -> dust::Result<TenantReports> { Ok(TenantReports::new(dust::context::get("tenant")))}dust-framework finds these services on its own, so you don't register them in src/app.rs. They may live in any module, as long as the module is declared, such as with pub mod services; in src/lib.rs. Rust only compiles declared modules, so dust-framework never sees a service in a file you haven't declared.
To register the service under a trait contract too, name the contract with as. This function registers the Mapbox geocoder from that section, in place of its singleton_as call in src/app.rs:
// src/services/mapbox.rsuse dust::container::singleton;#[singleton(as = dyn Geocoder)]async fn mapbox(config: Section<MapboxConfig>) -> dust::Result<Mapbox> { Ok(Mapbox::new(&config.token))}Handlers that take Inject<dyn Geocoder> and handlers that take Inject<Mapbox> now share the same instance.
Using services
In handlers
Handlers take an Inject<T> argument, which dereferences to the service:
use dust::prelude::*;use crate::services::stripe::Stripe;pub async fn store(stripe: Inject<Stripe>) -> dust::Result<Redirect> { stripe.charge(2_000).await?; Ok(Redirect::back())}Middleware functions, jobs, listeners, and console commands take services as Inject<T> arguments the same way.
Anywhere else
Code without handler arguments, such as a scheduled task or the closure given to once, can call dust::resolve. Resolving may build the service, so .await it:
use crate::services::stripe::Stripe;pub async fn charge_monthly_fee() -> dust::Result<()> { let stripe = dust::resolve::<Stripe>().await?; stripe.charge(1_000).await}dust::resolve works anywhere your application runs: in requests, commands, jobs, boot hooks, and tests.
Resolution can fail in two ways. A factory may return Err, which reaches the caller as the same error; the container does not cache a failure, so the next request tries the factory again. Or you may ask for a type that was never registered; the error names the type, and the fix is to register it in src/app.rs or with #[singleton]. Neither case panics.
A bind service is built inside the request that asks for it, so a handler that takes Inject<T> receives a fresh instance each time. Resolve it again in the same request and you get another instance, not the one the handler received. If two parts of one request must share the instance, resolve it once and pass it down, or register it as a singleton that takes the request values as method arguments.
When the application boots
dust-framework builds each service the first time something uses it, not when the application boots. If a factory fails, such as when its server is down, the first request that needs the service fails. To build a service at boot instead, resolve it in a booted callback in src/app.rs. The callback runs once, after every package's provider boots, and an error from it stops the application from booting:
// src/app.rsuse dust::Application;use crate::services::stripe::Stripe;Application::configure().booted(async |app| { app.resolve::<Stripe>().await?; Ok(())})Singletons and shared state
A singleton serves every request for as long as your application runs, and Inject<T> gives each request a shared reference to it, as an Arc would. So a service's fields hold what every request shares, never anything about one request. Pass the current user and other per-request values to its methods instead:
// src/services/checkout.rsuse std::sync::Arc;use std::sync::atomic::{AtomicU64, Ordering};use crate::models::User;use crate::services::stripe::Stripe;pub struct Checkout { stripe: Arc<Stripe>, orders: AtomicU64,}impl Checkout { pub fn new(stripe: Arc<Stripe>) -> Self { Self { stripe, orders: AtomicU64::new(0) } } pub async fn pay(&self, user: &User, cents: u64) -> dust::Result<()> { self.stripe.charge(cents).await?; self.orders.fetch_add(1, Ordering::Relaxed); tracing::info!(user.id = user.id, cents, "Checkout complete"); Ok(()) }}The handler passes in the logged-in user, so two customers checking out at the same moment never see each other's details:
use dust::prelude::*;use crate::models::User;use crate::services::checkout::Checkout;pub async fn store( user: Authenticated<User>, checkout: Inject<Checkout>,) -> dust::Result<Redirect> { checkout.pay(&user, 2_000).await?; Ok(Redirect::back())}orders counts every order the service takes, across all requests. pay only has &self, so the count is an AtomicU64, which it can update through a shared reference. For other data a service changes as it runs, use a Mutex, as you would for any value shared between threads.
[!NOTE] A handler that holds a standard
Mutexlock across an.awaitdoesn't compile, and the error points at its route: "this function can't handle requests". Add#[dust::routing::debug_handler]to the handler, and the compiler names the lock. Release the lock before the.await, or usetokio::sync::Mutexif you need to hold it.