Quick start
This page is for when you already know what dependency injection is and just want to see snapfit working. If you'd rather understand the problem first, start with Part 1; this page will still be here.
Three plain structs
A shop that loads its currency settings once, opens a catalog database that formats prices, and has a checkout that uses the database. Nothing here mentions snapfit:
#[derive(Default)]
pub struct ShopConfig {
pub currency: &'static str,
}
impl ShopConfig {
pub fn new() -> Self {
Self { currency: "USD" }
}
}
pub struct CatalogDb {
config: Arc<ShopConfig>,
}
impl CatalogDb {
pub fn new(config: Arc<ShopConfig>) -> Self {
Self { config }
}
pub fn format_price(&self, cents: u64) -> String {
format!(
"{}.{:02} {}",
cents / 100,
cents % 100,
self.config.currency
)
}
}
pub struct OrderCheckout {
db: Arc<CatalogDb>,
}
impl OrderCheckout {
pub fn new(db: Arc<CatalogDb>) -> Self {
Self { db }
}
pub fn receipt(&self, item: &str, cents: u64) -> String {
format!("charged {} for {item}", self.db.format_price(cents))
}
}One container
The container lists the three components and what each one needs:
#[container]
pub struct ShopContainer {
#[singleton]
config: Arc<ShopConfig>,
#[singleton(deps = [config])]
db: Arc<CatalogDb>,
#[singleton(deps = [db])]
checkout: Arc<OrderCheckout>,
}Run it
Build the container and ask it for the checkout:
fn main() {
let container = ShopContainer::new();
let checkout = container.get_checkout();
println!("{}", checkout.receipt("mechanical keyboard", 14500));
}It prints:
charged 145.00 USD for mechanical keyboardWhat you just saw
- Plain domain structs.
ShopConfig,CatalogDbandOrderCheckoutdon't importsnapfitor implement any of its traits (Chapter 6). - A component that needs nothing.
config: Arc<ShopConfig>has nodeps, soShopContainer::new()callsShopConfig::new()once and wraps it in anArc(Chapter 5). - Components that need others.
dblistsconfig, so it receives a clone of it inCatalogDb::new(...);checkoutlistsdband is built after it (Chapter 7). - One of each. Each component is built once, and
get_checkout()returns a clone of the sameArc<OrderCheckout>every time (Chapter 5).
Which problem this solves
Part 1 walks through the problems of wiring an application without snapfit, and Chapter 4 shows where each one is answered. On this page you met two of them:
- Tight coupling (Chapter 1):
OrderCheckoutreceives its database; onlyShopContainerdecides what it is. - Ordering by hand (Chapter 3): nobody orders the construction.
ShopContainer::new()builds each field after the fields itsdepslists.
Remember
- Domain structs stay plain Rust; only the container carries
snapfitattributes. - Every
#[singleton]is built once, after the fields it needs, and itsget_<name>()returns a clone of it.