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
use std::sync::Arc;

use crate::inject::Inject;
use crate::provider::Provider;
use crate::Container;
use crate::InjectError;
use std::marker::PhantomData;

pub struct InstanceProvider<T: Inject> {
    pub instance: Arc<T>,
}

impl<T: Inject> Provider for InstanceProvider<T> {
    type ProvidedType = Arc<T>;

    fn provide(&self, _: &Container) -> Result<Self::ProvidedType, InjectError> {
        Ok(self.instance.clone())
    }
}

impl<T: Inject> InstanceProvider<T> {
    pub fn new(instance: T) -> Self {
        Self {
            instance: Arc::from(instance),
        }
    }

    pub fn install_into(self, container: &mut Container) {
        let cloned = Arc::clone(&self.instance);
        container.install(self);
        container.install_ref(cloned);
    }
}

#[derive(Debug, Default)]
pub struct DefaultProvider<T: Inject + Default> {
    type_: PhantomData<T>,
}

impl<T: Inject + Default> DefaultProvider<T> {
    pub fn new() -> Self {
        Self::default()
    }
}

impl<T: Inject + Default> Provider for DefaultProvider<T> {
    type ProvidedType = T;

    fn provide(&self, _: &Container) -> Result<Self::ProvidedType, InjectError> {
        Ok(T::default())
    }
}