Skip to main content

ScopeFactory

Trait ScopeFactory 

Source
pub trait ScopeFactory: Send + Sync {
    // Required method
    fn create_scope(&self) -> Scope;
}
Expand description

Factory trait for creating independent scopes.

The built provider always offers an implementation (no manual registration required): provider.get::<dyn ScopeFactory>() and #[inject] Arc<dyn ScopeFactory> fields both work, including inside eagerly built singletons (e.g. background workers that need one scope per tick). Explicit singleton::<dyn ScopeFactory>(...) registrations take precedence.

The built-in implementation holds a Weak reference to the container, so a singleton may store it without creating an Arc cycle; the container must therefore outlive services created from it. 工厂 trait:创建独立 scope。可注入 singleton 服务按需创建 scope。

典型场景:后台 worker singleton 需要按请求创建独立 scope, 在 scope 内解析 Scoped 服务(如 request-scoped DbContext)。

built provider 内置此服务:provider.get::<dyn ScopeFactory>() 以及 #[inject] Arc<dyn ScopeFactory> 字段都可用,无需手动注册,eager singleton 与懒解析服务一致。显式 singleton::<dyn ScopeFactory>(...) 注册仍然优先(覆盖内置实现)。

内置实现持有 provider 的 Weak 引用,因此 singleton 持有它不会形成 容器 → singleton → 容器 的 Arc 环;容器必须先于其创建的服务存活 (create_scope 在 provider 已释放时会 panic,与 MEDI 的容器生命周期 约定一致)。若需要强引用语义,可自行注册实现。

Required Methods§

Source

fn create_scope(&self) -> Scope

创建一个独立 scope,共享 root 的 store/singleton_cache/named, 独立 scoped 缓存和 disposables。

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§