From 8e862c7998d0b59c71d20cbcbbc57031f734b6fa Mon Sep 17 00:00:00 2001 From: HampusM Date: Mon, 22 Aug 2022 19:13:19 +0200 Subject: refactor!: move specifying binding scope to a binding scope configurator BREAKING CHANGE: Specifying the scope of a DI container binding is now done with a binding scope configurator --- src/di_container.rs | 150 ++++++++++++++++++++++++++-------------- src/di_container_binding_map.rs | 15 ++-- src/errors/di_container.rs | 7 ++ 3 files changed, 116 insertions(+), 56 deletions(-) (limited to 'src') diff --git a/src/di_container.rs b/src/di_container.rs index c698fac..cc2a930 100644 --- a/src/di_container.rs +++ b/src/di_container.rs @@ -53,77 +53,118 @@ use std::marker::PhantomData; #[cfg(feature = "factory")] use crate::castable_factory::CastableFactory; use crate::di_container_binding_map::DIContainerBindingMap; -use crate::errors::di_container::{BindingBuilderError, DIContainerError}; +use crate::errors::di_container::{ + BindingBuilderError, BindingScopeConfiguratorError, DIContainerError, +}; use crate::interfaces::injectable::Injectable; use crate::libs::intertrait::cast::{CastBox, CastRc}; use crate::provider::{Providable, SingletonProvider, TransientTypeProvider}; use crate::ptr::{SingletonPtr, TransientPtr}; -/// Binding builder for type `Interface` inside a [`DIContainer`]. -pub struct BindingBuilder<'di_container_lt, Interface> +/// Scope configurator for a binding for type 'Interface' inside a [`DIContainer`]. +pub struct BindingScopeConfigurator<'di_container, Interface, Implementation> where Interface: 'static + ?Sized, + Implementation: Injectable, { - di_container: &'di_container_lt mut DIContainer, + di_container: &'di_container mut DIContainer, interface_phantom: PhantomData, + implementation_phantom: PhantomData, } -impl<'di_container_lt, Interface> BindingBuilder<'di_container_lt, Interface> +impl<'di_container, Interface, Implementation> + BindingScopeConfigurator<'di_container, Interface, Implementation> where Interface: 'static + ?Sized, + Implementation: Injectable, { - fn new(di_container: &'di_container_lt mut DIContainer) -> Self + fn new(di_container: &'di_container mut DIContainer) -> Self { Self { di_container, interface_phantom: PhantomData, + implementation_phantom: PhantomData, } } - /// Creates a binding of type `Interface` to type `Implementation` inside of the - /// associated [`DIContainer`]. + /// Configures the binding to be in a transient scope. /// - /// # Errors - /// Will return Err if the associated [`DIContainer`] already have a binding for - /// the interface. - pub fn to(&mut self) -> Result<(), BindingBuilderError> - where - Implementation: Injectable, + /// This is the default. + pub fn in_transient_scope(&mut self) { self.di_container .bindings - .set::(Box::new(TransientTypeProvider::::new())) - .ok_or_else(|| { - BindingBuilderError::BindingAlreadyExists(type_name::()) - })?; - - Ok(()) + .set::(Box::new(TransientTypeProvider::::new())); } - /// Creates a binding of type `Interface` to a new singleton of type `Implementation` - /// inside of the associated [`DIContainer`]. + /// Configures the binding to be in a singleton scope. /// /// # Errors - /// Will return Err if creating the singleton fails or if the - /// associated [`DIContainer`] already have a binding for the interface. - pub fn to_singleton(&mut self) -> Result<(), BindingBuilderError> - where - Implementation: Injectable, + /// Will return Err if resolving the implementation fails. + pub fn in_singleton_scope(&mut self) -> Result<(), BindingScopeConfiguratorError> { let singleton: SingletonPtr = SingletonPtr::from( Implementation::resolve(self.di_container, Vec::new()) - .map_err(BindingBuilderError::SingletonResolveFailed)?, + .map_err(BindingScopeConfiguratorError::SingletonResolveFailed)?, ); self.di_container .bindings - .set::(Box::new(SingletonProvider::new(singleton))) - .ok_or_else(|| { - BindingBuilderError::BindingAlreadyExists(type_name::()) - })?; + .set::(Box::new(SingletonProvider::new(singleton))); Ok(()) } +} + +/// Binding builder for type `Interface` inside a [`DIContainer`]. +pub struct BindingBuilder<'di_container, Interface> +where + Interface: 'static + ?Sized, +{ + di_container: &'di_container mut DIContainer, + interface_phantom: PhantomData, +} + +impl<'di_container, Interface> BindingBuilder<'di_container, Interface> +where + Interface: 'static + ?Sized, +{ + fn new(di_container: &'di_container mut DIContainer) -> Self + { + Self { + di_container, + interface_phantom: PhantomData, + } + } + + /// Creates a binding of type `Interface` to type `Implementation` inside of the + /// associated [`DIContainer`]. + /// + /// The scope of the binding is transient. But that can be changed by using the + /// returned [`BindingScopeConfigurator`] + /// + /// # Errors + /// Will return Err if the associated [`DIContainer`] already have a binding for + /// the interface. + pub fn to( + &mut self, + ) -> Result, BindingBuilderError> + where + Implementation: Injectable, + { + if self.di_container.bindings.has::() { + return Err(BindingBuilderError::BindingAlreadyExists(type_name::< + Interface, + >())); + } + + let mut binding_scope_configurator = + BindingScopeConfigurator::new(self.di_container); + + binding_scope_configurator.in_transient_scope(); + + Ok(binding_scope_configurator) + } /// Creates a binding of factory type `Interface` to a factory inside of the /// associated [`DIContainer`]. @@ -143,16 +184,19 @@ where Return: 'static + ?Sized, Interface: crate::interfaces::factory::IFactory, { + if self.di_container.bindings.has::() { + return Err(BindingBuilderError::BindingAlreadyExists(type_name::< + Interface, + >())); + } + let factory_impl = CastableFactory::new(factory_func); - self.di_container - .bindings - .set::(Box::new(crate::provider::FactoryProvider::new( - crate::ptr::FactoryPtr::new(factory_impl), - ))) - .ok_or_else(|| { - BindingBuilderError::BindingAlreadyExists(type_name::()) - })?; + self.di_container.bindings.set::(Box::new( + crate::provider::FactoryProvider::new(crate::ptr::FactoryPtr::new( + factory_impl, + )), + )); Ok(()) } @@ -173,16 +217,19 @@ where where Return: 'static + ?Sized, { + if self.di_container.bindings.has::() { + return Err(BindingBuilderError::BindingAlreadyExists(type_name::< + Interface, + >())); + } + let factory_impl = CastableFactory::new(factory_func); - self.di_container - .bindings - .set::(Box::new(crate::provider::FactoryProvider::new( - crate::ptr::FactoryPtr::new(factory_impl), - ))) - .ok_or_else(|| { - BindingBuilderError::BindingAlreadyExists(type_name::()) - })?; + self.di_container.bindings.set::(Box::new( + crate::provider::FactoryProvider::new(crate::ptr::FactoryPtr::new( + factory_impl, + )), + )); Ok(()) } @@ -364,6 +411,8 @@ impl Default for DIContainer #[cfg(test)] mod tests { + use std::error::Error; + use mockall::mock; use super::*; @@ -512,7 +561,7 @@ mod tests } #[test] - fn can_bind_to_singleton() -> Result<(), BindingBuilderError> + fn can_bind_to_singleton() -> Result<(), Box> { let mut di_container: DIContainer = DIContainer::new(); @@ -520,7 +569,8 @@ mod tests di_container .bind::() - .to_singleton::()?; + .to::()? + .in_singleton_scope()?; assert_eq!(di_container.bindings.count(), 1); diff --git a/src/di_container_binding_map.rs b/src/di_container_binding_map.rs index e64ff17..20d040f 100644 --- a/src/di_container_binding_map.rs +++ b/src/di_container_binding_map.rs @@ -31,19 +31,22 @@ impl DIContainerBindingMap .as_ref()) } - pub fn set(&mut self, provider: Box) -> Option<()> + pub fn set(&mut self, provider: Box) where Interface: 'static + ?Sized, { let interface_typeid = TypeId::of::(); - if self.bindings.contains_key(&interface_typeid) { - return None; - } - self.bindings.insert(interface_typeid, provider); + } + + pub fn has(&self) -> bool + where + Interface: 'static + ?Sized, + { + let interface_typeid = TypeId::of::(); - Some(()) + self.bindings.contains_key(&interface_typeid) } /// Only used by tests in the `di_container` module. diff --git a/src/errors/di_container.rs b/src/errors/di_container.rs index ed05a5e..98c2be4 100644 --- a/src/errors/di_container.rs +++ b/src/errors/di_container.rs @@ -54,7 +54,14 @@ pub enum BindingBuilderError /// A binding already exists for a interface. #[error("Binding already exists for interface '{0}'")] BindingAlreadyExists(&'static str), +} +/// Error type for [`BindingScopeConfigurator`]. +/// +/// [`BindingBuilder`]: crate::di_container::BindingScopeConfigurator +#[derive(thiserror::Error, Debug)] +pub enum BindingScopeConfiguratorError +{ /// Resolving a singleton failed. #[error("Resolving the given singleton failed")] SingletonResolveFailed(#[from] InjectableError), -- cgit v1.2.3-18-g5258