Skip to content

Service Container

Architecture Concepts

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, Laravel 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. Laravel 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.

Laravel registers its own services, such as the database, the cache, and the mailer, and you reach them through helpers such as laravel::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 laravel::mail::to(..), or laravel::resolve directly from them.

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:

1// src/services/stripe.rs
2use laravel::config::Section;
3use laravel::http::client;
4 
5#[derive(Clone, Section)]
6pub struct StripeConfig {
7 #[env("STRIPE_KEY", required)]
8 pub key: String,
9}
10 
11pub struct Stripe {
12 key: String,
13}
14 
15impl Stripe {
16 pub fn new(key: &str) -> Self {
17 Self { key: key.to_owned() }
18 }
19 
20 pub async fn charge(&self, cents: u64) -> laravel::Result<()> {
21 client::post("https://api.stripe.com/v1/payment_intents")
22 .token(&self.key)
23 .form([("amount", cents.to_string()), ("currency", "usd".to_owned())])
24 .await?;
25 
26 Ok(())
27 }
28}
1// src/services/stripe.rs
2use laravel::config::Section;
3use laravel::http::client;
4 
5#[derive(Clone, Section)]
6pub struct StripeConfig {
7 #[env("STRIPE_KEY", required)]
8 pub key: String,
9}
10 
11pub struct Stripe {
12 key: String,
13}
14 
15impl Stripe {
16 pub fn new(key: &str) -> Self {
17 Self { key: key.to_owned() }
18 }
19 
20 pub async fn charge(&self, cents: u64) -> laravel::Result<()> {
21 client::post("https://api.stripe.com/v1/payment_intents")
22 .token(&self.key)
23 .form([("amount", cents.to_string()), ("currency", "usd".to_owned())])
24 .await?;
25 
26 Ok(())
27 }
28}

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:

1// src/app.rs
2use laravel::Application;
3use laravel::foundation::ApplicationBuilder;
4 
5use crate::services::stripe::{Stripe, StripeConfig};
6 
7pub fn configure() -> ApplicationBuilder {
8 Application::configure().with_services(|app| {
9 app.singleton(async |app| {
10 let key = &app.config().section::<StripeConfig>().key;
11 
12 Ok(Stripe::new(key))
13 });
14 })
15}
1// src/app.rs
2use laravel::Application;
3use laravel::foundation::ApplicationBuilder;
4 
5use crate::services::stripe::{Stripe, StripeConfig};
6 
7pub fn configure() -> ApplicationBuilder {
8 Application::configure().with_services(|app| {
9 app.singleton(async |app| {
10 let key = &app.config().section::<StripeConfig>().key;
11 
12 Ok(Stripe::new(key))
13 });
14 })
15}

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 laravel::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:

1// src/app.rs
2use crate::services::pricing::Pricing;
3 
4app.instance(Pricing::new(0.07));
1// src/app.rs
2use crate::services::pricing::Pricing;
3 
4app.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.

Register the service itself, such as Stripe, rather than an Arc<Stripe>. The container already shares one instance, and Inject<Stripe> looks for it under Stripe. Keep Arc<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:

1// src/app.rs
2use laravel::context;
3 
4use crate::services::reports::TenantReports;
5 
6app.bind(async |_app| {
7 let tenant: Option<String> = context::get("tenant");
8 
9 Ok(TenantReports::new(tenant))
10});
1// src/app.rs
2use laravel::context;
3 
4use crate::services::reports::TenantReports;
5 
6app.bind(async |_app| {
7 let tenant: Option<String> = context::get("tenant");
8 
9 Ok(TenantReports::new(tenant))
10});

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:

1// src/services/checkout.rs
2use std::sync::Arc;
3 
4use crate::services::stripe::Stripe;
5 
6pub struct Checkout {
7 stripe: Arc<Stripe>,
8}
9 
10impl Checkout {
11 pub fn new(stripe: Arc<Stripe>) -> Self {
12 Self { stripe }
13 }
14 
15 pub async fn pay(&self, cents: u64) -> laravel::Result<()> {
16 self.stripe.charge(cents).await
17 }
18}
1// src/services/checkout.rs
2use std::sync::Arc;
3 
4use crate::services::stripe::Stripe;
5 
6pub struct Checkout {
7 stripe: Arc<Stripe>,
8}
9 
10impl Checkout {
11 pub fn new(stripe: Arc<Stripe>) -> Self {
12 Self { stripe }
13 }
14 
15 pub async fn pay(&self, cents: u64) -> laravel::Result<()> {
16 self.stripe.charge(cents).await
17 }
18}

In the factory, resolve the other service from the container. resolve returns it as an Arc<T>, ready to keep in a field:

1// src/app.rs
2app.singleton(async |app| {
3 let stripe = app.resolve::<Stripe>().await?;
4 
5 Ok(Checkout::new(stripe))
6});
1// src/app.rs
2app.singleton(async |app| {
3 let stripe = app.resolve::<Stripe>().await?;
4 
5 Ok(Checkout::new(stripe))
6});

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:

1[dependencies]
2async-trait = "0.1"
1[dependencies]
2async-trait = "0.1"

Define the contract:

1// src/services/geocoder.rs
2use async_trait::async_trait;
3 
4pub struct Coordinates {
5 pub latitude: f64,
6 pub longitude: f64,
7}
8 
9#[async_trait]
10pub trait Geocoder: Send + Sync {
11 async fn locate(&self, address: &str) -> laravel::Result<Coordinates>;
12}
1// src/services/geocoder.rs
2use async_trait::async_trait;
3 
4pub struct Coordinates {
5 pub latitude: f64,
6 pub longitude: f64,
7}
8 
9#[async_trait]
10pub trait Geocoder: Send + Sync {
11 async fn locate(&self, address: &str) -> laravel::Result<Coordinates>;
12}

Then implement it for Mapbox:

1// src/services/mapbox.rs
2use async_trait::async_trait;
3use laravel::config::Section;
4 
5use crate::services::geocoder::{Coordinates, Geocoder};
6 
7#[derive(Clone, Section)]
8pub struct MapboxConfig {
9 #[env("MAPBOX_TOKEN", required)]
10 pub token: String,
11}
12 
13pub struct Mapbox {
14 token: String,
15}
16 
17impl Mapbox {
18 pub fn new(token: &str) -> Self {
19 Self { token: token.to_owned() }
20 }
21}
22 
23#[async_trait]
24impl Geocoder for Mapbox {
25 async fn locate(&self, address: &str) -> laravel::Result<Coordinates> {
26 // Fetch the address's coordinates from Mapbox's API...
27 }
28}
1// src/services/mapbox.rs
2use async_trait::async_trait;
3use laravel::config::Section;
4 
5use crate::services::geocoder::{Coordinates, Geocoder};
6 
7#[derive(Clone, Section)]
8pub struct MapboxConfig {
9 #[env("MAPBOX_TOKEN", required)]
10 pub token: String,
11}
12 
13pub struct Mapbox {
14 token: String,
15}
16 
17impl Mapbox {
18 pub fn new(token: &str) -> Self {
19 Self { token: token.to_owned() }
20 }
21}
22 
23#[async_trait]
24impl Geocoder for Mapbox {
25 async fn locate(&self, address: &str) -> laravel::Result<Coordinates> {
26 // Fetch the address's coordinates from Mapbox's API...
27 }
28}

Register it with singleton_as, whose factory returns the service as an Arc<dyn Geocoder>:

1// src/app.rs
2use std::sync::Arc;
3 
4use crate::services::geocoder::Geocoder;
5use crate::services::mapbox::{Mapbox, MapboxConfig};
6 
7app.singleton_as(async |app| {
8 let token = &app.config().section::<MapboxConfig>().token;
9 
10 Ok(Arc::new(Mapbox::new(token)) as Arc<dyn Geocoder>)
11});
1// src/app.rs
2use std::sync::Arc;
3 
4use crate::services::geocoder::Geocoder;
5use crate::services::mapbox::{Mapbox, MapboxConfig};
6 
7app.singleton_as(async |app| {
8 let token = &app.config().section::<MapboxConfig>().token;
9 
10 Ok(Arc::new(Mapbox::new(token)) as Arc<dyn Geocoder>)
11});

Now your handlers can ask for the contract instead of Mapbox itself. This one looks up an address without knowing which service answers:

1use laravel::prelude::*;
2 
3use crate::services::geocoder::Geocoder;
4 
5pub async fn show(geocoder: Inject<dyn Geocoder>) -> laravel::Result<String> {
6 let place = geocoder.locate("1600 Pennsylvania Ave NW, Washington, DC").await?;
7 
8 Ok(format!("{}, {}", place.latitude, place.longitude))
9}
1use laravel::prelude::*;
2 
3use crate::services::geocoder::Geocoder;
4 
5pub async fn show(geocoder: Inject<dyn Geocoder>) -> laravel::Result<String> {
6 let place = geocoder.locate("1600 Pennsylvania Ave NW, Washington, DC").await?;
7 
8 Ok(format!("{}, {}", place.latitude, place.longitude))
9}

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:

1// src/app.rs
2Application::configure().with_services(|app| {
3 app.instance(Stripe::new("sk_test_..."));
4})
1// src/app.rs
2Application::configure().with_services(|app| {
3 app.instance(Stripe::new("sk_test_..."));
4})

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:

1// src/services/stripe.rs
2use laravel::container::singleton;
3 
4#[singleton]
5async fn stripe(config: Section<StripeConfig>) -> laravel::Result<Stripe> {
6 Ok(Stripe::new(&config.key))
7}
1// src/services/stripe.rs
2use laravel::container::singleton;
3 
4#[singleton]
5async fn stripe(config: Section<StripeConfig>) -> laravel::Result<Stripe> {
6 Ok(Stripe::new(&config.key))
7}

To build a fresh service each time something asks for it, use #[bind] instead:

1// src/services/reports.rs
2use laravel::container::bind;
3 
4#[bind]
5async fn tenant_reports() -> laravel::Result<TenantReports> {
6 Ok(TenantReports::new(laravel::context::get("tenant")))
7}
1// src/services/reports.rs
2use laravel::container::bind;
3 
4#[bind]
5async fn tenant_reports() -> laravel::Result<TenantReports> {
6 Ok(TenantReports::new(laravel::context::get("tenant")))
7}

Laravel 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 Laravel 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:

1// src/services/mapbox.rs
2use laravel::container::singleton;
3 
4#[singleton(as = dyn Geocoder)]
5async fn mapbox(config: Section<MapboxConfig>) -> laravel::Result<Mapbox> {
6 Ok(Mapbox::new(&config.token))
7}
1// src/services/mapbox.rs
2use laravel::container::singleton;
3 
4#[singleton(as = dyn Geocoder)]
5async fn mapbox(config: Section<MapboxConfig>) -> laravel::Result<Mapbox> {
6 Ok(Mapbox::new(&config.token))
7}

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:

1use laravel::prelude::*;
2 
3use crate::services::stripe::Stripe;
4 
5pub async fn store(stripe: Inject<Stripe>) -> laravel::Result<Redirect> {
6 stripe.charge(2_000).await?;
7 
8 Ok(Redirect::back())
9}
1use laravel::prelude::*;
2 
3use crate::services::stripe::Stripe;
4 
5pub async fn store(stripe: Inject<Stripe>) -> laravel::Result<Redirect> {
6 stripe.charge(2_000).await?;
7 
8 Ok(Redirect::back())
9}

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 laravel::resolve. Resolving may build the service, so .await it:

1use crate::services::stripe::Stripe;
2 
3pub async fn charge_monthly_fee() -> laravel::Result<()> {
4 let stripe = laravel::resolve::<Stripe>().await?;
5 
6 stripe.charge(1_000).await
7}
1use crate::services::stripe::Stripe;
2 
3pub async fn charge_monthly_fee() -> laravel::Result<()> {
4 let stripe = laravel::resolve::<Stripe>().await?;
5 
6 stripe.charge(1_000).await
7}

laravel::resolve works anywhere your application runs: in requests, commands, jobs, boot hooks, and tests.

When the application boots

Laravel 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:

1// src/app.rs
2use laravel::Application;
3 
4use crate::services::stripe::Stripe;
5 
6Application::configure().booted(async |app| {
7 app.resolve::<Stripe>().await?;
8 
9 Ok(())
10})
1// src/app.rs
2use laravel::Application;
3 
4use crate::services::stripe::Stripe;
5 
6Application::configure().booted(async |app| {
7 app.resolve::<Stripe>().await?;
8 
9 Ok(())
10})

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:

1// src/services/checkout.rs
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4 
5use crate::models::User;
6use crate::services::stripe::Stripe;
7 
8pub struct Checkout {
9 stripe: Arc<Stripe>,
10 orders: AtomicU64,
11}
12 
13impl Checkout {
14 pub fn new(stripe: Arc<Stripe>) -> Self {
15 Self { stripe, orders: AtomicU64::new(0) }
16 }
17 
18 pub async fn pay(&self, user: &User, cents: u64) -> laravel::Result<()> {
19 self.stripe.charge(cents).await?;
20 self.orders.fetch_add(1, Ordering::Relaxed);
21 
22 tracing::info!(user.id = user.id, cents, "Checkout complete");
23 
24 Ok(())
25 }
26}
1// src/services/checkout.rs
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4 
5use crate::models::User;
6use crate::services::stripe::Stripe;
7 
8pub struct Checkout {
9 stripe: Arc<Stripe>,
10 orders: AtomicU64,
11}
12 
13impl Checkout {
14 pub fn new(stripe: Arc<Stripe>) -> Self {
15 Self { stripe, orders: AtomicU64::new(0) }
16 }
17 
18 pub async fn pay(&self, user: &User, cents: u64) -> laravel::Result<()> {
19 self.stripe.charge(cents).await?;
20 self.orders.fetch_add(1, Ordering::Relaxed);
21 
22 tracing::info!(user.id = user.id, cents, "Checkout complete");
23 
24 Ok(())
25 }
26}

The handler passes in the logged-in user, so two customers checking out at the same moment never see each other's details:

1use laravel::prelude::*;
2 
3use crate::models::User;
4use crate::services::checkout::Checkout;
5 
6pub async fn store(
7 user: Authenticated<User>,
8 checkout: Inject<Checkout>,
9) -> laravel::Result<Redirect> {
10 checkout.pay(&user, 2_000).await?;
11 
12 Ok(Redirect::back())
13}
1use laravel::prelude::*;
2 
3use crate::models::User;
4use crate::services::checkout::Checkout;
5 
6pub async fn store(
7 user: Authenticated<User>,
8 checkout: Inject<Checkout>,
9) -> laravel::Result<Redirect> {
10 checkout.pay(&user, 2_000).await?;
11 
12 Ok(Redirect::back())
13}

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.

A handler that holds a standard Mutex lock across an .await doesn't compile, and the error points at its route: "this function can't handle requests". Add #[laravel::routing::debug_handler] to the handler, and the compiler names the lock. Release the lock before the .await, or use tokio::sync::Mutex if you need to hold it.