Skip to content

Instantly share code, notes, and snippets.

@n0mn0m
Created December 11, 2020 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n0mn0m/ac2c3fd30dbb9a2d6a4e13e5a679b8d1 to your computer and use it in GitHub Desktop.
Save n0mn0m/ac2c3fd30dbb9a2d6a4e13e5a679b8d1 to your computer and use it in GitHub Desktop.
DI Builder
//! Example based on the AutoFac 'getting started' example
//! (http://autofac.readthedocs.io/en/latest/getting-started/index.html)
use shaku::{module, Component, Interface};
use std::sync::Arc;
module! {
pub AutoFacModule {
components = [ConsoleOutput, TodayWriter],
providers = []
}
}
pub trait IOutput: Interface {
fn write(&self, content: String);
}
#[derive(Component)]
#[shaku(interface = IOutput)]
pub struct ConsoleOutput;
impl IOutput for ConsoleOutput {
fn write(&self, content: String) {
println!("{}", content);
}
}
pub trait IDateWriter: Interface {
fn write_date(&self);
fn get_date(&self) -> String;
}
#[derive(Component)]
#[shaku(interface = IDateWriter)]
pub struct TodayWriter {
#[shaku(inject)]
output: Arc<dyn IOutput>,
today: String,
year: usize,
}
impl IDateWriter for TodayWriter {
fn write_date(&self) {
self.output.write(self.get_date());
}
fn get_date(&self) -> String {
format!("Today is {}, {}", self.today, self.year)
}
}
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
mod autofac;
use crate::autofac::{AutoFacModule, IDateWriter, TodayWriter, TodayWriterParameters};
use shaku_rocket::Inject;
mod tests;
#[get("/")]
fn index(writer: Inject<AutoFacModule, dyn IDateWriter>) -> String {
writer.write_date();
writer.get_date()
}
fn configure_services() -> autofac::AutoFacModule {
AutoFacModule::builder()
.with_component_parameters::<TodayWriter>(TodayWriterParameters {
today: "June 19".to_string(),
year: 2020,
})
.build()
}
fn rocket(services: autofac::AutoFacModule) -> rocket::Rocket {
rocket::ignite().manage(services).mount("/", routes![index])
}
fn main() {
rocket(configure_services()).launch();
}
use crate::{configure_services, rocket};
use rocket::http::Status;
use rocket::local::Client;
#[test]
fn hello_world() {
let client = Client::new(rocket(configure_services())).unwrap();
let mut response = client.get("/").dispatch();
assert_eq!(response.status(), Status::Ok);
assert_eq!(
response.body_string(),
Some("Today is June 19, 2020".into())
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment