use std::marker::PhantomData; use std::rc::Rc; use crate::di_container::blocking::IDIContainer; use crate::errors::injectable::InjectableError; use crate::interfaces::injectable::Injectable; use crate::ptr::{SingletonPtr, TransientPtr}; #[derive(strum_macros::Display, Debug)] pub enum Providable where DIContainerType: IDIContainer, { Transient(TransientPtr>), Singleton(SingletonPtr>), #[cfg(feature = "factory")] Factory(crate::ptr::FactoryPtr), #[cfg(feature = "factory")] DefaultFactory( crate::ptr::FactoryPtr, ), } pub trait IProvider where DIContainerType: IDIContainer, { fn provide( &self, di_container: &Rc, dependency_history: Vec<&'static str>, ) -> Result, InjectableError>; } pub struct TransientTypeProvider where InjectableType: Injectable, DIContainerType: IDIContainer, { injectable_phantom: PhantomData, di_container_phantom: PhantomData, } impl TransientTypeProvider where InjectableType: Injectable, DIContainerType: IDIContainer, { pub fn new() -> Self { Self { injectable_phantom: PhantomData, di_container_phantom: PhantomData, } } } impl IProvider for TransientTypeProvider where InjectableType: Injectable, DIContainerType: IDIContainer, { fn provide( &self, di_container: &Rc, dependency_history: Vec<&'static str>, ) -> Result, InjectableError> { Ok(Providable::Transient(InjectableType::resolve( di_container, dependency_history, )?)) } } pub struct SingletonProvider where InjectableType: Injectable, DIContainerType: IDIContainer, { singleton: SingletonPtr, di_container_phantom: PhantomData, } impl SingletonProvider where InjectableType: Injectable, DIContainerType: IDIContainer, { pub fn new(singleton: SingletonPtr) -> Self { Self { singleton, di_container_phantom: PhantomData, } } } impl IProvider for SingletonProvider where InjectableType: Injectable, DIContainerType: IDIContainer, { fn provide( &self, _di_container: &Rc, _dependency_history: Vec<&'static str>, ) -> Result, InjectableError> { Ok(Providable::Singleton(self.singleton.clone())) } } #[cfg(feature = "factory")] pub struct FactoryProvider { factory: crate::ptr::FactoryPtr, is_default_factory: bool, } #[cfg(feature = "factory")] impl FactoryProvider { pub fn new( factory: crate::ptr::FactoryPtr, is_default_factory: bool, ) -> Self { Self { factory, is_default_factory, } } } #[cfg(feature = "factory")] impl IProvider for FactoryProvider where DIContainerType: IDIContainer, { fn provide( &self, _di_container: &Rc, _dependency_history: Vec<&'static str>, ) -> Result, InjectableError> { Ok(if self.is_default_factory { Providable::DefaultFactory(self.factory.clone()) } else { Providable::Factory(self.factory.clone()) }) } }