RSS Amplifier

Miguel Piedrafita · Dec 21, 2023

Exploring dependency injection in Rust.

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

use silhouette::facade::Container; struct DBPool {} struct DBConnection {} // will always use the same pool Container::singleton(&|_| DBPool::new())?; // will resolve a new connection each time Container::bind(&|container| -> DBConnection { let shared_pool = container.resolve::<DBPool>().unwrap(); shared_pool.get_conn() })?; // somewhere else in your app... let connection:…

use silhouette::facade::Container;
struct DBPool {}
struct DBConnection {}
// will always use the same pool
Container::singleton(&|_| DBPool::new())?;
// will resolve a new connection each time
Container::bind(&|container| -> DBConnection {
    let shared_pool = container.resolve::<DBPool>().unwrap();
    shared_pool.get_conn()
})?;
// somewhere else in your app...
let connection: DBConnection = Container::resolve()?;

Dependency injection is one of my favourite patterns (it's also the secret sauce behind Laravel), but Rust's type system and borrow checker make it impossible to fully implement.

Nevertheless, I wanted to see how far I could get, so I built a super simple service container that lets you register and resolve services, with support for singletons and closures. No interfaces tho 😅

View on GitHub

Read on miguel.build

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.