From e0f90a8e384615c79d7d51c66d19294d75e79391 Mon Sep 17 00:00:00 2001 From: HampusM Date: Sat, 27 Aug 2022 23:41:41 +0200 Subject: feat: implement named bindings --- src/di_container_binding_map.rs | 59 +++++++++++++++++++++++++++++++++++------ 1 file changed, 51 insertions(+), 8 deletions(-) (limited to 'src/di_container_binding_map.rs') diff --git a/src/di_container_binding_map.rs b/src/di_container_binding_map.rs index 20d040f..d4b46f2 100644 --- a/src/di_container_binding_map.rs +++ b/src/di_container_binding_map.rs @@ -4,9 +4,16 @@ use ahash::AHashMap; use crate::{errors::di_container::DIContainerError, provider::IProvider}; +#[derive(Debug, PartialEq, Eq, Hash)] +struct DIContainerBindingKey +{ + type_id: TypeId, + name: Option<&'static str>, +} + pub struct DIContainerBindingMap { - bindings: AHashMap>, + bindings: AHashMap>, } impl DIContainerBindingMap @@ -18,7 +25,10 @@ impl DIContainerBindingMap } } - pub fn get(&self) -> Result<&dyn IProvider, DIContainerError> + pub fn get( + &self, + name: Option<&'static str>, + ) -> Result<&dyn IProvider, DIContainerError> where Interface: 'static + ?Sized, { @@ -26,27 +36,60 @@ impl DIContainerBindingMap Ok(self .bindings - .get(&interface_typeid) - .ok_or_else(|| DIContainerError::BindingNotFound(type_name::()))? + .get(&DIContainerBindingKey { + type_id: interface_typeid, + name, + }) + .ok_or_else(|| DIContainerError::BindingNotFound { + interface: type_name::(), + name, + })? .as_ref()) } - pub fn set(&mut self, provider: Box) + pub fn set( + &mut self, + name: Option<&'static str>, + provider: Box, + ) where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); + + self.bindings.insert( + DIContainerBindingKey { + type_id: interface_typeid, + name, + }, + provider, + ); + } + + pub fn remove( + &mut self, + name: Option<&'static str>, + ) -> Option> where Interface: 'static + ?Sized, { let interface_typeid = TypeId::of::(); - self.bindings.insert(interface_typeid, provider); + self.bindings.remove(&DIContainerBindingKey { + type_id: interface_typeid, + name, + }) } - pub fn has(&self) -> bool + pub fn has(&self, name: Option<&'static str>) -> bool where Interface: 'static + ?Sized, { let interface_typeid = TypeId::of::(); - self.bindings.contains_key(&interface_typeid) + self.bindings.contains_key(&DIContainerBindingKey { + type_id: interface_typeid, + name, + }) } /// Only used by tests in the `di_container` module. -- cgit v1.2.3-18-g5258