tx_di
基于 proc_macro + linkme 的 Rust 依赖注入框架。编译期收集元数据,运行期自动拓扑排序并注入,零反射、零运行时扫描。
快速上手
依赖
[]
= "0.2"
基本用法
use Arc;
use ;
// 无依赖单例
;
// 带自定义值
// 依赖其他组件
async
属性宏 #[tx_comp]
| 写法 | 说明 |
|---|---|
#[tx_comp] |
默认 Singleton |
#[tx_comp(scope = Prototype)] |
每次注入创建新实例 |
#[tx_comp(scope)] |
同 Prototype |
#[tx_comp(init)] |
自行实现 CompInit trait |
#[tx_comp(conf)] |
从 TOML 配置自动反序列化 |
#[tx_comp(conf = "key")] |
指定 TOML 配置键 |
#[tx_comp(as_trait = dyn Trait)] |
注册为 trait 实现,支持 trait object 注入 |
可组合使用:#[tx_comp(scope = Prototype, as_trait = dyn MyTrait)]
字段注入
| 写法 | 语义 |
|---|---|
field: Arc<T> |
从 DI 容器注入,按 T 的 scope 处理 |
#[tx_cst(expr)] |
直接用表达式赋值,不进依赖图 |
#[tx_cst(skip)] |
跳过,使用 Default::default() |
Option<T> 字段 |
自动设为 None |
Trait Object 注入
通过 as_trait 将具体类型注册为 trait 实现,注入时自动解析。
要求:trait 需要 Any + Send + Sync 作为 supertrait。
// 定义 trait
// 注册实现
// 注入 trait object
一个 trait 可以有多个实现,通过 inject_all_traits_from_store 获取全部:
let repos: = inject_all_traits_from_store;
作用域 Scope
| 作用域 | 行为 |
|---|---|
| Singleton(默认) | 全局唯一,首次注入时构建并缓存 |
| Prototype | 每次 inject() 创建新实例 |
scope 标记在被注入者上,消费者只需写 Arc<T>。
配置组件
# configs/app.toml
[]
= "production"
= 9090
use Deserialize;
// 从 [my_config] 加载
// 自定义键名
加载配置文件:
let ctx = new;
let ctx = ; // 不用配置
自定义初始化 CompInit
use ;
use async_method;
BuildContext & App
// 构建阶段
let ctx = new;
let db: = ctx.;
debug_registry; // 打印注册表
let app: App = ctx.build?; // 固化
// 或快捷方式
ctx.build_and_run.await?; // build + init + async_init
// App 阶段(支持 Singleton 和 Prototype)
let app = new;
let db = app.;
let logger = app.; // Prototype 每次新建
// 异步运行(后台任务管理)
let app = ctx.ins_run.await?; // 返回 Arc<App>,后台初始化
app.waiting_exit.await; // 等待 Ctrl+C 信号
约束
| 约束 | 原因 |
|---|---|
组件需 T: Send + Sync + 'static |
存入 Arc<dyn Any + Send + Sync> |
配置组件需 Deserialize + Default |
serde 反序列化 |
trait 注入需 Trait: Any + Send + Sync |
TypeId::of::<dyn Trait>() 要求 |
| 避免循环依赖 | 拓扑排序检测,存在则 panic |
插件 crate 必须 use 导入 |
linkme 依赖链接器 |
许可证
MIT