use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;
use axum::extract::FromRef;
#[derive(Clone, Default)]
pub struct Container {
services: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}
impl Container {
pub fn new() -> Self {
Self::default()
}
pub fn insert<T: ?Sized + Send + Sync + 'static>(&mut self, value: Arc<T>) {
self.services
.insert(TypeId::of::<Arc<T>>(), Arc::new(value));
}
pub fn get<T: ?Sized + Send + Sync + 'static>(&self) -> Option<Arc<T>> {
let any_arc = self.services.get(&TypeId::of::<Arc<T>>())?;
any_arc.downcast_ref::<Arc<T>>().cloned()
}
}
impl<T: ?Sized + Send + Sync + 'static> FromRef<Container> for Arc<T> {
fn from_ref(container: &Container) -> Arc<T> {
container.get::<T>().unwrap_or_else(|| {
panic!(
"service Arc<{}> not registered in App container",
std::any::type_name::<T>()
)
})
}
}
pub trait Injectable {}