From 6813690e893bc461bd2be60509850a5a80454c6a Mon Sep 17 00:00:00 2001 From: HampusM Date: Sun, 18 Sep 2022 20:20:53 +0200 Subject: feat: add binding async factories to async DI container --- examples/async-factory/main.rs | 65 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/async-factory/main.rs (limited to 'examples') diff --git a/examples/async-factory/main.rs b/examples/async-factory/main.rs new file mode 100644 index 0000000..74e12c7 --- /dev/null +++ b/examples/async-factory/main.rs @@ -0,0 +1,65 @@ +#![deny(clippy::all)] +#![deny(clippy::pedantic)] +#![allow(clippy::module_name_repetitions)] + +use anyhow::Result; +use syrette::{async_closure, factory, AsyncDIContainer}; + +trait IFoo +{ + fn bar(&self); +} + +#[factory(async = true)] +type IFooFactory = dyn Fn(i32) -> dyn IFoo; + +struct Foo +{ + cnt: i32, +} + +impl Foo +{ + fn new(cnt: i32) -> Self + { + Self { cnt } + } +} + +impl IFoo for Foo +{ + fn bar(&self) + { + for _ in 1..self.cnt { + println!("Foobar"); + } + } +} + +#[tokio::main] +async fn main() -> Result<()> +{ + let mut di_container = AsyncDIContainer::new(); + + di_container + .bind::() + .to_async_factory(&|_| { + async_closure!(|cnt| { + let foo = Box::new(Foo::new(cnt)); + + foo as Box + }) + }) + .await?; + + let foo_factory = di_container + .get::() + .await? + .threadsafe_factory()?; + + let foo = foo_factory(4).await; + + foo.bar(); + + Ok(()) +} -- cgit v1.2.3-18-g5258