Skip to main content

sword_core/injectables/
providers.rs

1use crate::{Injectable, RwMap};
2use std::{any::TypeId, collections::HashMap, sync::Arc};
3
4/// Marker trait for pre-instantiated dependencies (providers).
5///
6/// Providers are dependencies that have been pre-constructed and registered
7/// into the State. Unlike Components which are built from their dependencies,
8/// Providers are already complete instances that only need to be retrieved
9/// from the State.
10///
11/// Providers are injected as `Arc<T>` (via `State::borrow`), so they do not
12/// need to be `Clone`. Common use cases: database connections, external API
13/// clients, or any resource that requires async initialization or complex setup.
14pub trait Provider: Send + Sync {}
15
16pub struct ProviderRegistry {
17    providers: RwMap<TypeId, Injectable>,
18}
19
20impl ProviderRegistry {
21    pub(crate) fn new() -> Self {
22        Self {
23            providers: RwMap::new(HashMap::new()),
24        }
25    }
26
27    /// Registers a provider instance.
28    ///
29    /// Providers are instances that have already been constructed and are ready
30    /// to be injected into other components. Typical use cases include database
31    /// connections, HTTP clients, or external service configurations that cannot
32    /// be auto-constructed from the State.
33    pub fn register<T>(&self, provider: T)
34    where
35        T: Provider + 'static,
36    {
37        self.providers
38            .write()
39            .insert(TypeId::of::<T>(), Arc::new(provider));
40    }
41
42    pub(crate) fn get_providers(&self) -> &RwMap<TypeId, Injectable> {
43        &self.providers
44    }
45}