aboutsummaryrefslogtreecommitdiff
path: root/src/di_container/blocking/binding/when_configurator.rs
blob: 5b9a8c09ade9cb08a053cd4cd792ae82d7870809 (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
//! When configurator for a binding for types inside of a [`IDIContainer`].
//!
//! [`IDIContainer`]: crate::di_container::blocking::IDIContainer
use std::any::type_name;
use std::marker::PhantomData;
use std::rc::Rc;

use crate::di_container::blocking::IDIContainer;
use crate::errors::di_container::BindingWhenConfiguratorError;

/// When configurator for a binding for type 'Interface' inside a [`IDIContainer`].
///
/// [`IDIContainer`]: crate::di_container::blocking::IDIContainer
pub struct BindingWhenConfigurator<Interface, DIContainerType>
where
    Interface: 'static + ?Sized,
    DIContainerType: IDIContainer,
{
    di_container: Rc<DIContainerType>,
    interface_phantom: PhantomData<Interface>,
}

impl<Interface, DIContainerType> BindingWhenConfigurator<Interface, DIContainerType>
where
    Interface: 'static + ?Sized,
    DIContainerType: IDIContainer,
{
    pub(crate) fn new(di_container: Rc<DIContainerType>) -> Self
    {
        Self {
            di_container,
            interface_phantom: PhantomData,
        }
    }

    /// Configures the binding to have a name.
    ///
    /// # Errors
    /// Will return Err if no binding for the interface already exists.
    pub fn when_named(
        &self,
        name: &'static str,
    ) -> Result<(), BindingWhenConfiguratorError>
    {
        let binding = self
            .di_container
            .remove_binding::<Interface>(None)
            .map_or_else(
                || {
                    Err(BindingWhenConfiguratorError::BindingNotFound(type_name::<
                        Interface,
                    >(
                    )))
                },
                Ok,
            )?;

        self.di_container
            .set_binding::<Interface>(Some(name), binding);

        Ok(())
    }
}