Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

依赖注入模式

#[inject] 模式(推荐)

#![allow(unused)]
fn main() {
#[derive(Inject)]
pub struct GetDocContentHandler {
    #[inject]
    docs: Arc<dyn IDocumentService>,
}

#[handler(inject)]
#[async_trait]
impl IRequestHandler<GetDocContentRequest, DocContent> for GetDocContentHandler { ... }
}

两者分工:

  1. #[derive(Inject)] 只生成构造函数(__rdi_construct_GetDocContentHandler)
  2. #[handler(inject)] 让 inventory 工厂在每个请求调用该构造函数,在请求作用域内解析 字段依赖(如 Arc<dyn IDocumentService>),并提交 HandlerRegistration

因此它是编译期、按请求的处理器工厂,不是 DI 里的 singleton;也不会向 DI 注册 dyn IRequestHandler<...>——HTTP 分发通过 inventory HandlerCache 查找,不查 DI。

字段只有标注 #[inject] 时才从容器解析(Arc<T> / Option<Arc<T>> / Vec<Arc<T>>, 或用 #[inject(owned)] 解析 bare T);未标注的字段一律取 Default::default()。

框架内置可注入服务

Host 构建时注册以下服务,Handler / IHostedService 直接注入:

服务用途
Arc<dyn IEndpointCatalog>运行时端点元数据:all() / get() / localized()
Arc<dyn IStringLocalizer>资源键查找,默认 culture 来自 Culture.Default
#![allow(unused)]
fn main() {
#[derive(Inject)]
pub struct ListEndpointsHandler {
    #[inject]
    catalog: Arc<dyn IEndpointCatalog>,
    #[inject]
    localizer: Arc<dyn IStringLocalizer>,
}

// handle 中:
// let all = self.catalog.all();                 // &[EndpointDescriptor]
// let rows = self.catalog.localized(&*self.localizer); // Vec<EndpointInfo>
}

Host::endpoints() 与 Host::localizer() 也可直接取得同一对象,用于 main 或测试代码。

IDynamicAuthorizer 也是由 #[inject] impl 自动收集的单例,但它是路由授权器、不是普通注入 依赖;用法见 动态授权。

业务服务:接口在 contracts,实现在 handlers

Handler 和 IHostedService 只依赖 trait,不依赖具体实现类型。

#![allow(unused)]
fn main() {
// contracts/docs/service.rs — 接口与 DTO(仅依赖框架)
pub trait IDocumentService: Send + Sync {
    fn list_works(&self) -> Result<Vec<String>, String>;
    fn content(&self, work: &str, path: &str) -> Result<DocContent, String>;
}

// handlers/doc_service.rs — 实现,并在 impl 块上注册
#[derive(Inject)]
pub struct DocService;

#[inject]
impl IDocumentService for DocService { ... }

// handlers/docs/get_doc_content.rs — Handler 消费接口
#[derive(Inject)]
pub struct GetDocContentHandler {
    #[inject]
    docs: Arc<dyn IDocumentService>,
}
}

要点:

层级位置依赖类型注册方式
接口 traitcontracts/—无注册
Service 实现handlers/无,或 Arc<…>#[derive(Inject)] + impl 块上的 #[inject]
Handlerhandlers/Arc<dyn IDocumentService>#[derive(Inject)] + #[handler(inject)]

新增业务能力时:先在 contracts 写 trait + DTO → 在 handlers 写实现并在 impl 块上加 #[inject] → Handler 注入 Arc<dyn I…Service>,无需改 main.rs。

组合根:只注册基础设施

main.rs 用 HostBuilder 注册 rust-dix 无法自行构造的基础设施。扩展方法写在 host/src/startup/services/:

#![allow(unused)]
fn main() {
Host::builder()
    .register(move |svc| svc.add_docbit_db(db))   // SQLite DbContext(共享 Arc<DbContextOptions>)
    .use_spa("wwwroot")
    .use_authentication()
    .build();
}
#![allow(unused)]
fn main() {
// host/src/startup/services/service_collection.rs
impl ServiceCollectionExt for ServiceCollection {
    fn add_docbit_db(self, options: Arc<DbContextOptions>) -> Self {
        self.scoped(move |_| Arc::new(DbContext::from_options(&options).unwrap()))
    }
}
}

业务 Service(如 DocService)不在此手动注册——由 impl 块上的 #[inject] 自动收集。

DbContext(rust-ef)

DbContext 是 Scoped 依赖:每个请求作用域一份实例;后台任务用自己的 scope。

#![allow(unused)]
fn main() {
// Handler:按请求解析(#[handler(inject)] 的 factory 在请求 scope 内 get_owned)
#[derive(Inject)]
struct SaveHandler {
    #[inject(owned)]
    ctx: DbContext,
}

// IHostedService:注入 rust-dix 内建的 ScopeFactory,显式开 scope
#[derive(Inject)]
struct DbInitService {
    #[inject]
    services: Arc<dyn ScopeFactory>,
}

async fn start(&self) -> Result<()> {
    let scope = self.services.create_scope();
    // `RdiError` → `webx::Error` 的 `From` 已提供,直接 `?`
    let mut ctx: DbContext = scope.get_owned()?;
    // ...
    Ok(())
}
}

实体与领域逻辑在 domain/。建表分两种:生产库走 rust-ef 的版本化迁移 (ctx.migrate("Migrations") 或新库 ctx.bootstrap(),配套 MigrationStore、 MigrationEngine::diff/apply_diff、has_drift() 接 readiness);参考应用与测试在启动时用 ctx.ensure_created() 直接按模型建表(仅演示/测试用途)。

服务间依赖链

GetDocContentHandler (handlers/)
    → Arc<dyn IDocumentService>   (DocService in handlers/)
        → <app_base>/docs/{work}  (webx::app_base())
        → domain entities

依赖在编译期由字段类型声明,运行时由 DI 容器解析。

反模式

❌ 反模式✅ 替代
I…Service trait 放在 services/ 或 handlers/ 私有模块trait 定义在 contracts/
Handler 依赖 Arc<DocService> 具体类型Arc<dyn IDocumentService>
在 main.rs 逐个 singleton::<DocService>在 impl 块上加 #[inject] 自动注册
contracts 引用 domain 类型作为 ResponseDTO 定义在 contracts,handlers 中映射
Handler 内 UserRepository::new()DI 注入 Arc<dyn I…Service>
Handler 间直接调用IMediator::send()

小结

生产项目统一使用 contracts 定义接口 + handlers 实现 + #[inject] + #[handler(inject)], main.rs 只做 Host 与基础设施配置。

下一节:IHostedService 后台服务