Skip to main content

sword_core/injectables/
providers.rs

1use crate::{FromState, 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 via the FromState trait.
10///
11/// Common use cases: database connections, external API clients, or any
12/// resource that requires async initialization or complex setup.
13pub trait Provider: FromState + Send + Sync {}
14
15pub struct ProviderRegistry {
16    providers: RwMap<TypeId, Injectable>,
17}
18
19impl ProviderRegistry {
20    pub(crate) fn new() -> Self {
21        Self {
22            providers: RwMap::new(HashMap::new()),
23        }
24    }
25
26    /// Registers a provider instance.
27    ///
28    /// Providers are instances that have already been constructed and are ready
29    /// to be injected into other components. Typical use cases include database
30    /// connections, HTTP clients, or external service configurations that cannot
31    /// be auto-constructed from the State.
32    pub fn register<T>(&self, provider: T)
33    where
34        T: Provider + 'static,
35    {
36        self.providers
37            .write()
38            .insert(TypeId::of::<T>(), Arc::new(provider));
39    }
40
41    pub(crate) fn get_providers(&self) -> &RwMap<TypeId, Injectable> {
42        &self.providers
43    }
44}