//! Dependency injection container and other related utilities. //! //! # Examples //! ``` //! use std::collections::HashMap; //! //! use syrette::{DIContainer, injectable}; //! use syrette::errors::di_container::DIContainerError; //! //! trait IDatabaseService //! { //! fn get_all_records(&self, table_name: String) -> HashMap; //! } //! //! struct DatabaseService {} //! //! #[injectable(IDatabaseService)] //! impl DatabaseService //! { //! fn new() -> Self //! { //! Self {} //! } //! } //! //! impl IDatabaseService for DatabaseService //! { //! fn get_all_records(&self, table_name: String) -> HashMap //! { //! // Do stuff here //! HashMap::::new() //! } //! } //! //! fn main() -> Result<(), String> //! { //! let mut di_container = DIContainer::new(); //! //! di_container.bind::().to::().map_err(|err| { //! err.to_string() //! })?; //! //! let database_service = di_container.get::().map_err(|err| { //! err.to_string() //! })?; //! //! Ok(()) //! } //! ``` use std::any::type_name; 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, BindingScopeConfiguratorError, DIContainerError, }; use crate::interfaces::injectable::Injectable; use crate::libs::intertrait::cast::{CastBox, CastRc}; use crate::provider::{Providable, SingletonProvider, TransientTypeProvider}; use crate::ptr::{SingletonPtr, SomePtr}; /// 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 mut DIContainer, interface_phantom: PhantomData, implementation_phantom: PhantomData, } impl<'di_container, Interface, Implementation> BindingScopeConfigurator<'di_container, Interface, Implementation> where Interface: 'static + ?Sized, Implementation: Injectable, { fn new(di_container: &'di_container mut DIContainer) -> Self { Self { di_container, interface_phantom: PhantomData, implementation_phantom: PhantomData, } } /// Configures the binding to be in a transient scope. /// /// This is the default. pub fn in_transient_scope(&mut self) { self.di_container .bindings .set::(Box::new(TransientTypeProvider::::new())); } /// Configures the binding to be in a singleton scope. /// /// # Errors /// 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(BindingScopeConfiguratorError::SingletonResolveFailed)?, ); self.di_container .bindings .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`]. /// /// *This function is only available if Syrette is built with the "factory" feature.* /// /// # Errors /// Will return Err if the associated [`DIContainer`] already have a binding for /// the interface. #[cfg(feature = "factory")] pub fn to_factory( &mut self, factory_func: &'static dyn Fn>, ) -> Result<(), BindingBuilderError> where Args: 'static, 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(()) } /// Creates a binding of type `Interface` to a factory that takes no arguments /// inside of the associated [`DIContainer`]. /// /// *This function is only available if Syrette is built with the "factory" feature.* /// /// # Errors /// Will return Err if the associated [`DIContainer`] already have a binding for /// the interface. #[cfg(feature = "factory")] pub fn to_default_factory( &mut self, factory_func: &'static dyn Fn<(), Output = crate::ptr::TransientPtr>, ) -> Result<(), BindingBuilderError> 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(()) } } /// Dependency injection container. pub struct DIContainer { bindings: DIContainerBindingMap, } impl DIContainer { /// Returns a new `DIContainer`. #[must_use] pub fn new() -> Self { Self { bindings: DIContainerBindingMap::new(), } } /// Returns a new [`BindingBuilder`] for the given interface. pub fn bind(&mut self) -> BindingBuilder where Interface: 'static + ?Sized, { BindingBuilder::::new(self) } /// Returns the type bound with `Interface`. /// /// # Errors /// Will return `Err` if: /// - No binding for `Interface` exists /// - Resolving the binding for `Interface` fails /// - Casting the binding for `Interface` fails pub fn get(&self) -> Result, DIContainerError> where Interface: 'static + ?Sized, { self.get_bound::(Vec::new()) } #[doc(hidden)] pub fn get_bound( &self, dependency_history: Vec<&'static str>, ) -> Result, DIContainerError> where Interface: 'static + ?Sized, { let binding_providable = self.get_binding_providable::(dependency_history)?; match binding_providable { Providable::Transient(transient_binding) => Ok(SomePtr::Transient( transient_binding.cast::().map_err(|_| { DIContainerError::CastFailed(type_name::()) })?, )), Providable::Singleton(singleton_binding) => Ok(SomePtr::Singleton( singleton_binding.cast::().map_err(|_| { DIContainerError::CastFailed(type_name::()) })?, )), #[cfg(feature = "factory")] Providable::Factory(factory_binding) => { match factory_binding.clone().cast::() { Ok(factory) => Ok(SomePtr::Factory(factory)), Err(_err) => { use crate::interfaces::factory::IFactory; let default_factory = factory_binding .cast::>() .map_err(|_| { DIContainerError::CastFailed(type_name::()) })?; Ok(SomePtr::Transient(default_factory())) } } } #[cfg(not(feature = "factory"))] Providable::Factory(_) => { return Err(DIContainerError::CantHandleFactoryBinding(type_name::< Interface, >( ))); } } } fn get_binding_providable( &self, dependency_history: Vec<&'static str>, ) -> Result where Interface: 'static + ?Sized, { self.bindings .get::()? .provide(self, dependency_history) .map_err(|err| DIContainerError::BindingResolveFailed { reason: err, interface: type_name::(), }) } } impl Default for DIContainer { fn default() -> Self { Self::new() } } #[cfg(test)] mod tests { use std::error::Error; use mockall::mock; use super::*; use crate::errors::injectable::InjectableError; use crate::provider::IProvider; use crate::ptr::TransientPtr; mod subjects { //! Test subjects. use std::fmt::Debug; use syrette_macros::declare_interface; use super::DIContainer; use crate::interfaces::injectable::Injectable; use crate::ptr::TransientPtr; pub trait IUserManager { fn add_user(&self, user_id: i128); fn remove_user(&self, user_id: i128); } pub struct UserManager {} impl UserManager { pub fn new() -> Self { Self {} } } impl IUserManager for UserManager { fn add_user(&self, _user_id: i128) { // ... } fn remove_user(&self, _user_id: i128) { // ... } } use crate as syrette; declare_interface!(UserManager -> IUserManager); impl Injectable for UserManager { fn resolve( _di_container: &DIContainer, _dependency_history: Vec<&'static str>, ) -> Result, crate::errors::injectable::InjectableError> where Self: Sized, { Ok(TransientPtr::new(Self::new())) } } pub trait INumber { fn get(&self) -> i32; fn set(&mut self, number: i32); } impl PartialEq for dyn INumber { fn eq(&self, other: &Self) -> bool { self.get() == other.get() } } impl Debug for dyn INumber { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(format!("{}", self.get()).as_str()) } } pub struct Number { pub num: i32, } impl Number { pub fn new() -> Self { Self { num: 0 } } } impl INumber for Number { fn get(&self) -> i32 { self.num } fn set(&mut self, number: i32) { self.num = number; } } declare_interface!(Number -> INumber); impl Injectable for Number { fn resolve( _di_container: &DIContainer, _dependency_history: Vec<&'static str>, ) -> Result, crate::errors::injectable::InjectableError> where Self: Sized, { Ok(TransientPtr::new(Self::new())) } } } #[test] fn can_bind_to() -> Result<(), Box> { let mut di_container: DIContainer = DIContainer::new(); assert_eq!(di_container.bindings.count(), 0); di_container .bind::() .to::()?; assert_eq!(di_container.bindings.count(), 1); Ok(()) } #[test] fn can_bind_to_singleton() -> Result<(), Box> { let mut di_container: DIContainer = DIContainer::new(); assert_eq!(di_container.bindings.count(), 0); di_container .bind::() .to::()? .in_singleton_scope()?; assert_eq!(di_container.bindings.count(), 1); Ok(()) } #[test] #[cfg(feature = "factory")] fn can_bind_to_factory() -> Result<(), Box> { type IUserManagerFactory = dyn crate::interfaces::factory::IFactory<(), dyn subjects::IUserManager>; let mut di_container: DIContainer = DIContainer::new(); assert_eq!(di_container.bindings.count(), 0); di_container.bind::().to_factory(&|| { let user_manager: TransientPtr = TransientPtr::new(subjects::UserManager::new()); user_manager })?; assert_eq!(di_container.bindings.count(), 1); Ok(()) } #[test] fn can_get() -> Result<(), Box> { mock! { Provider {} impl IProvider for Provider { fn provide( &self, di_container: &DIContainer, dependency_history: Vec<&'static str>, ) -> Result; } } let mut di_container: DIContainer = DIContainer::new(); let mut mock_provider = MockProvider::new(); mock_provider.expect_provide().returning(|_, _| { Ok(Providable::Transient(TransientPtr::new( subjects::UserManager::new(), ))) }); di_container .bindings .set::(Box::new(mock_provider)); di_container.get::()?; Ok(()) } #[test] fn can_get_singleton() -> Result<(), Box> { mock! { Provider {} impl IProvider for Provider { fn provide( &self, di_container: &DIContainer, dependency_history: Vec<&'static str>, ) -> Result; } } let mut di_container: DIContainer = DIContainer::new(); let mut mock_provider = MockProvider::new(); let mut singleton = SingletonPtr::new(subjects::Number::new()); SingletonPtr::get_mut(&mut singleton).unwrap().num = 2820; mock_provider .expect_provide() .returning_st(move |_, _| Ok(Providable::Singleton(singleton.clone()))); di_container .bindings .set::(Box::new(mock_provider)); let first_number_rc = di_container.get::()?.singleton()?; assert_eq!(first_number_rc.get(), 2820); let second_number_rc = di_container.get::()?.singleton()?; assert_eq!(first_number_rc.as_ref(), second_number_rc.as_ref()); Ok(()) } #[test] #[cfg(feature = "factory")] fn can_get_factory() -> Result<(), Box> { trait IUserManager { fn add_user(&mut self, user_id: i128); fn remove_user(&mut self, user_id: i128); } struct UserManager { users: Vec, } impl UserManager { fn new(users: Vec) -> Self { Self { users } } } impl IUserManager for UserManager { fn add_user(&mut self, user_id: i128) { self.users.push(user_id); } fn remove_user(&mut self, user_id: i128) { let user_index = self.users.iter().position(|user| *user == user_id).unwrap(); self.users.remove(user_index); } } use crate as syrette; #[crate::factory] type IUserManagerFactory = dyn crate::interfaces::factory::IFactory<(Vec,), dyn IUserManager>; mock! { Provider {} impl IProvider for Provider { fn provide( &self, di_container: &DIContainer, dependency_history: Vec<&'static str>, ) -> Result; } } let mut di_container: DIContainer = DIContainer::new(); let mut mock_provider = MockProvider::new(); mock_provider.expect_provide().returning(|_, _| { Ok(Providable::Factory(crate::ptr::FactoryPtr::new( CastableFactory::new(&|users| { let user_manager: TransientPtr = TransientPtr::new(UserManager::new(users)); user_manager }), ))) }); di_container .bindings .set::(Box::new(mock_provider)); di_container.get::()?; Ok(()) } }