aboutsummaryrefslogtreecommitdiff
path: root/example/src/main.rs
blob: 28f29b4907990649d7dfa436e8d0dae405305635 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
use std::rc::Rc;

use syrette::errors::di_container::DIContainerError;
use syrette::factory;
use syrette::interfaces::factory::IFactory;
use syrette::{injectable, DIContainer};

trait IDog
{
    fn woof(&self);
}

struct Dog {}

#[injectable(IDog)]
impl Dog
{
    fn new() -> Self
    {
        Self {}
    }
}

impl IDog for Dog
{
    fn woof(&self)
    {
        println!("Woof!");
    }
}

trait ICat
{
    fn meow(&self);
}

struct Cat {}

#[injectable(ICat)]
impl Cat
{
    fn new() -> Self
    {
        Self {}
    }
}

impl ICat for Cat
{
    fn meow(&self)
    {
        println!("Meow!");
    }
}

trait ICow
{
    fn moo(&self);
}

struct Cow
{
    _moo_cnt: i32,
}

impl Cow
{
    fn new(moo_cnt: i32) -> Self
    {
        Self { _moo_cnt: moo_cnt }
    }
}

impl ICow for Cow
{
    fn moo(&self)
    {
        for _ in 0..self._moo_cnt {
            println!("Moo");
        }
    }
}

#[factory]
type CowFactory = dyn IFactory<(i32,), dyn ICow>;

trait IHuman
{
    fn make_pets_make_sounds(&self);
}

struct Human
{
    _dog: Box<dyn IDog>,
    _cat: Box<dyn ICat>,
    _cow_factory: Rc<CowFactory>,
}

#[injectable(IHuman)]
impl Human
{
    fn new(dog: Box<dyn IDog>, cat: Box<dyn ICat>, cow_factory: Rc<CowFactory>) -> Self
    {
        Self {
            _dog: dog,
            _cat: cat,
            _cow_factory: cow_factory,
        }
    }
}

impl IHuman for Human
{
    fn make_pets_make_sounds(&self)
    {
        println!("Hi doggy!");

        self._dog.woof();

        println!("Hi kitty!");

        self._cat.meow();

        let cow: Box<dyn ICow> = (self._cow_factory)(3);

        cow.moo();
    }
}

fn main() -> error_stack::Result<(), DIContainerError>
{
    println!("Hello, world!");

    let mut di_container: DIContainer = DIContainer::new();

    di_container.bind::<dyn IDog>().to::<Dog>();
    di_container.bind::<dyn ICat>().to::<Cat>();
    di_container.bind::<dyn IHuman>().to::<Human>();

    di_container.bind::<CowFactory>().to_factory(&|moo_cnt| {
        let cow: Box<dyn ICow> = Box::new(Cow::new(moo_cnt));
        cow
    });

    let dog = di_container.get::<dyn IDog>()?;

    dog.woof();

    let human = di_container.get::<dyn IHuman>()?;

    human.make_pets_make_sounds();

    Ok(())
}