Expand description
请求作用域中间件 — DI Scoped 生命周期集成
P1-ARCH-DI-02 修复:将 DI 容器的 Scoped 生命周期集成到请求生命周期。
§问题
Container::scoped() + make_with_scope() + clear_scope() 已实现且有测试覆盖,
但整个代码库中无任何中间件调用这些方法。Scoped 生命周期在生产中等价于 Transient,
是死代码。
§解决方案
本中间件在每个请求开始时生成唯一 ScopeId,通过线程本地存储(thread-local)
使请求处理链中的任意代码都能通过 App::global().make::<T>() 透明地获得
Scoped 语义;请求结束时自动调用 clear_scope 释放作用域内所有缓存实例。
§使用
ⓘ
use sz_rust_core::middleware::request_scope::RequestScopeLayer;
use tower::ServiceBuilder;
let service = ServiceBuilder::new()
.layer(RequestScopeLayer::new())
.service(inner);业务代码无需任何改动:
ⓘ
// 注册 Scoped 服务(通常在 App::init 中)
App::with(|app| {
app.scoped(|| RequestCache::new());
});
// 请求处理中 — 同一请求内多次 make 返回同一实例
let cache = App::global().unwrap().make::<RequestCache>();Structs§
- Request
Scope Layer - 请求作用域 Layer(对齐 PHP 请求生命周期中的
app()->scoped()语义) - Request
Scope Service - 请求作用域 Service(由
RequestScopeLayer创建)
Functions§
- current_
scope_ id - 获取当前线程的请求作用域 ID