aboutsummaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2022-09-18 20:20:53 +0200
committerHampusM <hampus@hampusmat.com>2022-09-18 20:20:53 +0200
commit6813690e893bc461bd2be60509850a5a80454c6a (patch)
treef84e5321a0f608beda6b3abbf82de5c9496efc3e /examples
parent0b914f415cb04c45d8655cae3828af264887d203 (diff)
feat: add binding async factories to async DI container
Diffstat (limited to 'examples')
-rw-r--r--examples/async-factory/main.rs65
1 files changed, 65 insertions, 0 deletions
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::<IFooFactory>()
+ .to_async_factory(&|_| {
+ async_closure!(|cnt| {
+ let foo = Box::new(Foo::new(cnt));
+
+ foo as Box<dyn IFoo>
+ })
+ })
+ .await?;
+
+ let foo_factory = di_container
+ .get::<IFooFactory>()
+ .await?
+ .threadsafe_factory()?;
+
+ let foo = foo_factory(4).await;
+
+ foo.bar();
+
+ Ok(())
+}