From fdd7f824fd1244226ca86f525f8439744676688f Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 24 Sep 2022 17:31:16 +0200 Subject: feat: add bind async default factories to async DI container --- examples/async-factory/main.rs | 62 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 6 deletions(-) (limited to 'examples') diff --git a/examples/async-factory/main.rs b/examples/async-factory/main.rs index 74e12c7..715abf5 100644 --- a/examples/async-factory/main.rs +++ b/examples/async-factory/main.rs @@ -2,10 +2,14 @@ #![deny(clippy::pedantic)] #![allow(clippy::module_name_repetitions)] +use std::time::Duration; + use anyhow::Result; -use syrette::{async_closure, factory, AsyncDIContainer}; +use syrette::ptr::TransientPtr; +use syrette::{async_closure, declare_default_factory, factory, AsyncDIContainer}; +use tokio::time::sleep; -trait IFoo +trait IFoo: Send + Sync { fn bar(&self); } @@ -36,6 +40,34 @@ impl IFoo for Foo } } +trait IPerson: Send + Sync +{ + fn name(&self) -> String; +} + +struct Person +{ + name: String, +} + +impl Person +{ + fn new(name: String) -> Self + { + Self { name } + } +} + +impl IPerson for Person +{ + fn name(&self) -> String + { + self.name.clone() + } +} + +declare_default_factory!(dyn IPerson, async = true); + #[tokio::main] async fn main() -> Result<()> { @@ -45,9 +77,23 @@ async fn main() -> Result<()> .bind::() .to_async_factory(&|_| { async_closure!(|cnt| { - let foo = Box::new(Foo::new(cnt)); + let foo_ptr = Box::new(Foo::new(cnt)); - foo as Box + foo_ptr as Box + }) + }) + .await?; + + di_container + .bind::() + .to_async_default_factory(&|_| { + async_closure!(|| { + // Do some time demanding thing... + sleep(Duration::from_secs(1)).await; + + let person = TransientPtr::new(Person::new("Bob".to_string())); + + person as TransientPtr }) }) .await?; @@ -57,9 +103,13 @@ async fn main() -> Result<()> .await? .threadsafe_factory()?; - let foo = foo_factory(4).await; + let foo_ptr = foo_factory(4).await; + + foo_ptr.bar(); + + let person = di_container.get::().await?.transient()?; - foo.bar(); + println!("Person name is {}", person.name()); Ok(()) } -- cgit v1.2.3-18-g5258