From 7de7f73963a266cceff85d6ab71c3256e5d382ec Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 17 Sep 2022 18:33:43 +0200 Subject: feat!: allow factories to access async DI container BREAKING CHANGE: The to_factory & to_default_factory methods of AsyncBindingBuilder now expects a function returning a factory function --- examples/async/bootstrap.rs | 30 ++++++++++++++++++++++++++---- examples/async/interfaces/mod.rs | 1 + examples/async/main.rs | 12 ++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) (limited to 'examples') diff --git a/examples/async/bootstrap.rs b/examples/async/bootstrap.rs index 7e1d2cd..51af067 100644 --- a/examples/async/bootstrap.rs +++ b/examples/async/bootstrap.rs @@ -2,17 +2,20 @@ use std::sync::Arc; use anyhow::Result; use syrette::async_di_container::AsyncDIContainer; +use syrette::declare_default_factory; +use syrette::ptr::TransientPtr; -// Concrete implementations use crate::animals::cat::Cat; use crate::animals::dog::Dog; use crate::animals::human::Human; -// -// Interfaces +use crate::food::Food; use crate::interfaces::cat::ICat; use crate::interfaces::dog::IDog; +use crate::interfaces::food::{IFood, IFoodFactory}; use crate::interfaces::human::IHuman; +declare_default_factory!(dyn ICat, threadsafe = true); + pub async fn bootstrap() -> Result> { let mut di_container = AsyncDIContainer::new(); @@ -24,8 +27,27 @@ pub async fn bootstrap() -> Result> .in_singleton_scope() .await?; - di_container.bind::().to::().await?; + di_container + .bind::() + .to_default_factory(&|_| { + let cat: TransientPtr = TransientPtr::new(Cat::new()); + + cat + }) + .await?; + di_container.bind::().to::().await?; + di_container + .bind::() + .to_factory(&|_| { + Box::new(|| { + let food: Box = Box::new(Food::new()); + + food + }) + }) + .await?; + Ok(di_container) } diff --git a/examples/async/interfaces/mod.rs b/examples/async/interfaces/mod.rs index 5444978..ea0a26d 100644 --- a/examples/async/interfaces/mod.rs +++ b/examples/async/interfaces/mod.rs @@ -1,3 +1,4 @@ pub mod cat; pub mod dog; +pub mod food; pub mod human; diff --git a/examples/async/main.rs b/examples/async/main.rs index 3c884fe..03e36e1 100644 --- a/examples/async/main.rs +++ b/examples/async/main.rs @@ -7,12 +7,15 @@ use tokio::spawn; mod animals; mod bootstrap; +mod food; mod interfaces; use bootstrap::bootstrap; use interfaces::dog::IDog; use interfaces::human::IHuman; +use crate::interfaces::food::IFoodFactory; + #[tokio::main] async fn main() -> Result<()> { @@ -29,6 +32,15 @@ async fn main() -> Result<()> dog.woof(); } + let food_factory = di_container + .get::() + .await? + .threadsafe_factory()?; + + let food = food_factory(); + + food.eat(); + spawn(async move { let human = di_container.get::().await?.transient()?; -- cgit v1.2.3-18-g5258