aboutsummaryrefslogtreecommitdiff
path: root/examples/async-factory/main.rs
blob: 74e12c7aab5d064c4fef9261d185ff556ab59304 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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(())
}