MARY.WIN

RUSTY — LARAVEL TO RUST — 09

Dependency assembly versus
service-container resolution

Wire an application once and prove that the real caller receives its collaborator.
Tutorial 9 of 16 in From Laravel to Rust. Before you start: Tutorial 8.

Where does the application choose its executor? In examples/src/bin/ep09.rs, main() passes Preview into one Runner. It passes RecordingFake into another. Calling Runner::run() must use the executor stored in that runner.

A Laravel container can select an implementation through a binding. This Rust example makes the selection with Runner::new(executor). The constructor stores the supplied value. The Runner then retains that executor for later calls.

Follow construction from main() into the executor field, then follow invocation from Runner::run() to Executor::execute(). The fake’s distinct output will show whether the selected implementation reached the caller.

This lesson covers where a dependency is chosen and how to prove the choice arrives. We'll follow one value from main() into the executor field of a Runner<E>, follow one call from Runner::run() to Executor::execute(), and then break that path on purpose to show that the test notices. Along the way we'll compare the arrangement with Laravel's container. It leaves out building a container, factories, and registries. It assumes Tutorial 8.

Take a look at Example 1.

Example 1. Complete example (examples/src/bin/ep09.rs)

trait Executor {
    fn execute(&self, title: &str) -> String;
}

struct Preview;
impl Executor for Preview {
    fn execute(&self, title: &str) -> String {
        format!("preview: {title}")
    }
}

struct RecordingFake { prefix: String }
impl Executor for RecordingFake {
    fn execute(&self, title: &str) -> String {
        format!("{}: {title}", self.prefix)
    }
}

struct Runner<E> { executor: E }
impl<E: Executor> Runner<E> {
    fn new(executor: E) -> Self { Self { executor } }
    fn run(&self, title: &str) -> String {
        self.executor.execute(title)
    }
}

fn main() {
    let app = Runner::new(Preview);
    assert_eq!(app.run("tests"), "preview: tests");

    let probe = Runner::new(RecordingFake {
        prefix: "chosen by test".into(),
    });
    assert_eq!(probe.run("tests"), "chosen by test: tests");
    println!("the caller controls assembly");
}

Run it, and once both assertions pass it prints one line:

TERMINAL
cargo run --quiet --bin ep09
the caller controls assembly

The runner that became two types

Runner<E> had no opinion about executors. It held one field, executor: E, and its constructor was a single line, Self { executor }, which kept whatever it was handed the way a coat hook keeps whatever coat is hung on it. It understood itself to be one struct with one job. main built it twice, once around Preview and once around a RecordingFake carrying the words chosen by test, and the compiler had made two types of it: Runner<Preview> and Runner<RecordingFake>.

Sometimes a class has an interface, a constructor parameter, and a test double, and you still can't say which implementation a real call ends up using. Thankfully, in this example the answer is a path you can trace in three steps. Take another look at Example 1.

main() supplies a value to Runner::new(). The constructor stores it in the executor field. And Runner::run() invokes self.executor.execute(title), so every call goes to whatever was stored. main walks that path twice: app holds Preview, and probe holds a RecordingFake whose prefix is chosen by test.

That prefix is the signal. The assertion on probe.run("tests") expects chosen by test: tests, and that output can satisfy the assertion only if the runner uses the supplied fake's behavior. After both assertions pass, the terminal prints the caller controls assembly.

Ownership is part of construction

Runner<E> owns its executor: E field. Runner::new(executor) moves the supplied value into that field. Runner::run(&self, title) borrows the runner, and its self.executor.execute(title) call borrows the stored executor.

That arrangement is a design choice, and you can also make others. If several operations need one collaborator, you might pass references from an owner with a sufficient lifetime. If tasks genuinely need shared ownership, Arc may fit. A constructor does not settle every later lifetime question; it makes the current ownership relationship visible.

The E parameter appears on both Runner<E> and impl<E: Executor> Runner<E>, which is why app has type Runner<Preview> and probe has type Runner<RecordingFake>. Those are different concrete types. A runtime choice that needs one field type could instead use a compatible boxed trait object. You don't need that machinery merely because an application has dependencies, and if you're unsure, I'd start from the variability the program actually has.

How does Laravel do this?

In Laravel, a controller can request a service through its constructor, and a service provider can register the interface-to-implementation binding. That is still dependency injection: the collaborator arrives from outside the consumer, and the container performs the assembly.

Calling the container from inside every business operation changes the visibility of the dependency, since the function signature may then look empty while execution requires storage, a clock, and a network client, and that is, depending on the framework integration and on how the application is tested and on who has to find those three things later, a reasonable choice or a discovery problem, and the signature will not say which.

Container use is not bad by default, and hand wiring is not good by default. The question is whether the choice happens at a boundary you control, and whether the application's lifetime matches the object's intended lifetime.¹

In the Rust example, main is a small composition root: the place where concrete parts become a usable application. Configuration belongs nearby. Parse it, validate it, construct the appropriate adapter, then pass the assembled operation into the rest of the program.

How much machinery?

There is a temptation to put every constructor behind a factory and every factory behind a registry. Each additional mechanism should answer a concrete need: delayed construction, runtime selection, resource pooling, or an integration boundary. This example has one capability and one assembly point, and that is enough to demonstrate the principle. If the application grows, change the composition code then.

So the route works here. The same check belongs at your application's real entry points, and the questions there are about lifecycle, not about whether interfaces are fashionable. Take one feature and its entry point: the HTTP request, the queued job, or the console command. Can it reach the substituted implementation? Was the fake bound before the consumer was resolved, or after? Is a cached driver still holding the old object?

Testing

The test that matters here is a deliberate break. Change Runner::run() to call Preview.execute(title) directly. probe still stores a RecordingFake, but run() now bypasses that field, so the second assertion receives preview: tests instead of chosen by test: tests. This change was run on rustc 1.100.0 in a copy of the file saved as tmp/ep09_bypass.rs, which is the path in the first line. It exited with status 101:

OUTPUT
thread 'main' (32) panicked at tmp/ep09_bypass.rs:34:5:
assertion `left == right` failed
  left: "preview: tests"
 right: "chosen by test: tests"
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Restore self.executor.execute(title) afterward and run again. The break shows that the fake-prefix assertion detects a broken substitution path, rather than restating the implementation.

You can also extend the path. Add a PrefixExecutor whose prefix comes from a command-line argument. Before you change Runner, decide where argument parsing belongs, and trace the path you expect from input to execute().

Once you've made that prediction, compare it with this. main() parses the argument, constructs PrefixExecutor, then passes it to Runner::new(). Runner::run() continues to call the stored executor, and Runner does not need to read process arguments. That leaves two tests: missing configuration at the process boundary, and the configured prefix through Runner as a separate substitution check.

TL;DR

The substitution path in Example 1 has three steps: main() supplies the executor, Runner::new() stores it, and Runner::run() invokes the stored value. A fake with a distinct prefix shows whether the chosen executor reached the caller. Runner<E> owns its executor, and each choice of E is its own concrete type. Laravel's container performs the assembly through bindings; here main is the composition root. One deliberate bypass shows that the fake-prefix assertion detects a break in the path, and the same check belongs at a Laravel application's actual request, job, or command entry point.

¹ Laravel's singleton and scoped bindings have different reuse behavior. A long-running worker makes that difference more consequential than a short isolated request might suggest.

The sources.

Every program, its output and every compiler message were recorded on rustc 1.100.0 on 2026-11-20. Each page lists what was not checked.

Laravel 13 container and service-provider documentation; Martin Fowler, Inversion of Control Containers and the Dependency Injection Pattern; Rust Book, traits and trait objects. The bypass experiment is an original teaching example.

NOT CHECKED — 2
  • The PrefixExecutor exercise asks for new code. It was not written or run.
  • The statements about Laravel's container (constructor injection, provider bindings, singleton and scoped reuse, a fake bound after the consumer was resolved, a cached driver keeping the old object) follow the Laravel 13 documentation. No Laravel application was run.