blob: 920d9f05d27dc73ace63937c5a97d6a1feb25e36 (
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
|
use syrette::{injectable, DIContainer, DIContainerError};
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);
}
trait IHuman
{
fn make_pets_make_sounds(&self);
}
struct Human
{
_dog: Box<dyn IDog>,
_cat: Box<dyn ICat>,
}
#[injectable(IHuman)]
impl Human
{
fn new(dog: Box<dyn IDog>, cat: Box<dyn ICat>) -> Self
{
Self {
_dog: dog,
_cat: cat,
}
}
}
impl IHuman for Human
{
fn make_pets_make_sounds(&self)
{
println!("Hi doggy!");
self._dog.woof();
println!("Hi kitty!");
self._cat.meow();
}
}
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>();
let dog = di_container.get::<dyn IDog>()?;
dog.woof();
let human = di_container.get::<dyn IHuman>()?;
human.make_pets_make_sounds();
Ok(())
}
|