Skip to main content

injection/
component.rs

1use crate::container::InjectionContainer;
2use serde::Serialize;
3use std::any::Any;
4
5/// 组件 trait,所有可被依赖注入的组件都必须实现此 trait
6/// 该 trait 要求类型必须是线程安全的(Send + Sync),并且可以是任何类型(Any)
7pub trait Component: Any + Send + Sync {
8    /// 获取组件的名称,用于在容器中唯一标识该组件
9    /// 默认实现使用结构体的下划线命名格式
10    fn component_name() -> &'static str;
11    
12    /// 初始化组件
13    /// 这是一个异步方法,返回一个 Future,最终产生一个静态引用的组件实例
14    /// 该方法在容器预热或首次请求时调用
15    fn from_container() -> impl Future<Output = &'static Self> + Send;
16
17    /// 销毁组件时的清理操作(可选实现)
18    /// 这是一个异步方法,在组件销毁前调用
19    /// 默认实现为空操作
20    fn destroy(&self) -> impl Future<Output = ()> + Send{
21        async{}
22    }
23}
24
25/// 配置 trait,用于标记可以从配置文件加载的配置结构体
26/// 仅在启用 "config" 特性时可用
27#[cfg(feature = "config")]
28pub trait Configure: serde::de::DeserializeOwned+ Serialize + Default + Send + Sync + 'static {
29    /// 获取配置的前缀键名
30    /// 用于从配置文件中提取对应的配置节
31    fn prefix() -> &'static str;
32    
33    /// 从容器中加载配置
34    /// 默认实现从 InjectionContainer 中获取对应前缀的配置
35    fn from_container() -> Self {
36        InjectionContainer::get_config()
37    }
38}