aboutsummaryrefslogtreecommitdiff
path: root/src/async_di_container.rs
diff options
context:
space:
mode:
authorHampusM <hampus@hampusmat.com>2022-09-18 20:20:53 +0200
committerHampusM <hampus@hampusmat.com>2022-09-18 20:20:53 +0200
commit6813690e893bc461bd2be60509850a5a80454c6a (patch)
treef84e5321a0f608beda6b3abbf82de5c9496efc3e /src/async_di_container.rs
parent0b914f415cb04c45d8655cae3828af264887d203 (diff)
feat: add binding async factories to async DI container
Diffstat (limited to 'src/async_di_container.rs')
-rw-r--r--src/async_di_container.rs48
1 files changed, 48 insertions, 0 deletions
diff --git a/src/async_di_container.rs b/src/async_di_container.rs
index 7dcca57..1ead116 100644
--- a/src/async_di_container.rs
+++ b/src/async_di_container.rs
@@ -294,6 +294,54 @@ where
Ok(AsyncBindingWhenConfigurator::new(self.di_container.clone()))
}
+ /// Creates a binding of factory type `Interface` to a async factory inside of the
+ /// associated [`AsyncDIContainer`].
+ ///
+ /// *This function is only available if Syrette is built with the "factory" and
+ /// "async" features.*
+ ///
+ /// # Errors
+ /// Will return Err if the associated [`AsyncDIContainer`] already have a binding for
+ /// the interface.
+ #[cfg(all(feature = "factory", feature = "async"))]
+ pub async fn to_async_factory<Args, Return, FactoryFunc>(
+ &self,
+ factory_func: &'static FactoryFunc,
+ ) -> Result<AsyncBindingWhenConfigurator<Interface>, AsyncBindingBuilderError>
+ where
+ Args: 'static,
+ Return: 'static + ?Sized,
+ Interface: Fn<Args, Output = crate::future::BoxFuture<'static, Return>>,
+ FactoryFunc: Fn<
+ (Arc<AsyncDIContainer>,),
+ Output = Box<
+ (dyn Fn<Args, Output = crate::future::BoxFuture<'static, Return>>),
+ >,
+ > + Send
+ + Sync,
+ {
+ let mut bindings_lock = self.di_container.bindings.lock().await;
+
+ if bindings_lock.has::<Interface>(None) {
+ return Err(AsyncBindingBuilderError::BindingAlreadyExists(type_name::<
+ Interface,
+ >(
+ )));
+ }
+
+ let factory_impl = ThreadsafeCastableFactory::new(factory_func);
+
+ bindings_lock.set::<Interface>(
+ None,
+ Box::new(crate::provider::r#async::AsyncFactoryProvider::new(
+ crate::ptr::ThreadsafeFactoryPtr::new(factory_impl),
+ false,
+ )),
+ );
+
+ Ok(AsyncBindingWhenConfigurator::new(self.di_container.clone()))
+ }
+
/// Creates a binding of type `Interface` to a factory that takes no arguments
/// inside of the associated [`AsyncDIContainer`].
///