From 05be92b334af1beab3e7a3f2ee7626eb26c47e22 Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 16 Jul 2022 12:02:54 +0200 Subject: feat: add binding factories to DI container --- example/src/main.rs | 43 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) (limited to 'example/src/main.rs') diff --git a/example/src/main.rs b/example/src/main.rs index 1f23179..28f29b4 100644 --- a/example/src/main.rs +++ b/example/src/main.rs @@ -1,4 +1,8 @@ +use std::rc::Rc; + use syrette::errors::di_container::DIContainerError; +use syrette::factory; +use syrette::interfaces::factory::IFactory; use syrette::{injectable, DIContainer}; trait IDog @@ -54,6 +58,32 @@ trait ICow fn moo(&self); } +struct Cow +{ + _moo_cnt: i32, +} + +impl Cow +{ + fn new(moo_cnt: i32) -> Self + { + Self { _moo_cnt: moo_cnt } + } +} + +impl ICow for Cow +{ + fn moo(&self) + { + for _ in 0..self._moo_cnt { + println!("Moo"); + } + } +} + +#[factory] +type CowFactory = dyn IFactory<(i32,), dyn ICow>; + trait IHuman { fn make_pets_make_sounds(&self); @@ -63,16 +93,18 @@ struct Human { _dog: Box, _cat: Box, + _cow_factory: Rc, } #[injectable(IHuman)] impl Human { - fn new(dog: Box, cat: Box) -> Self + fn new(dog: Box, cat: Box, cow_factory: Rc) -> Self { Self { _dog: dog, _cat: cat, + _cow_factory: cow_factory, } } } @@ -88,6 +120,10 @@ impl IHuman for Human println!("Hi kitty!"); self._cat.meow(); + + let cow: Box = (self._cow_factory)(3); + + cow.moo(); } } @@ -101,6 +137,11 @@ fn main() -> error_stack::Result<(), DIContainerError> di_container.bind::().to::(); di_container.bind::().to::(); + di_container.bind::().to_factory(&|moo_cnt| { + let cow: Box = Box::new(Cow::new(moo_cnt)); + cow + }); + let dog = di_container.get::()?; dog.woof(); -- cgit v1.2.3-18-g5258