Skip to main content

Component

Trait Component 

Source
pub trait Component:
    Send
    + Sync
    + 'static {
    type Deps: DepsTuple;

    const SCOPE: Scope = Scope::Singleton;

    // Required method
    fn build(deps: Self::Deps) -> Self;

    // Provided methods
    fn inner_init(&mut self, store: &Store) -> RIE<()> { ... }
    fn init(app: &Arc<App>) -> RIE<()> { ... }
    fn async_init(app: &Arc<App>) -> BoxFuture<RIE<()>> { ... }
    fn async_run(app: &Arc<App>, token: CancellationToken) -> BoxFuture<RIE<()>> { ... }
    fn shutdown(&self) { ... }
    fn init_sort() -> i32 { ... }
    fn trait_impls() -> &'static [fn() -> TypeId] { ... }
}
Expand description

组件 trait — 每个被 DI 管理的类型都实现此 trait

#[derive(Component)] 自动生成(新宏),或手动实现。

§核心设计

  • Deps associated type 声明依赖,编译期类型可知
  • build() 是纯函数,从依赖构建自身
  • 生命周期钩子全部有默认实现

§生命周期

  1. build() — 构造实例(由宏生成)
  2. inner_init() — build 后同步初始化(可选)
  3. init() — 同步初始化(可选)
  4. async_init() — 异步初始化(可选)
  5. run() — 异步运行,长期任务(可选)
  6. shutdown() — 优雅关闭(可选)

Provided Associated Constants§

Source

const SCOPE: Scope = Scope::Singleton

作用域,默认 Singleton

Required Associated Types§

Source

type Deps: DepsTuple

依赖元组,编译期类型可知

例如:type Deps = (Arc<DbPool>, Arc<AppConfig>);

无依赖时用 ()

Required Methods§

Source

fn build(deps: Self::Deps) -> Self

从依赖构建组件实例

这是一个纯函数,不接触 Store,只接收已解析的依赖。

Provided Methods§

Source

fn inner_init(&mut self, store: &Store) -> RIE<()>

build 之后、init 之前调用(同步初始化)

可以访问 Store 注入额外依赖,但主要依赖应通过 Deps 声明。

Source

fn init(app: &Arc<App>) -> RIE<()>

同步初始化(在 App 阶段调用)

可以访问整个 App,用于跨组件协作初始化。

Source

fn async_init(app: &Arc<App>) -> BoxFuture<RIE<()>>

异步初始化(在 tokio runtime 里调用)

Source

fn async_run(app: &Arc<App>, token: CancellationToken) -> BoxFuture<RIE<()>>

异步运行(在独立 task 里调用,直到 CancellationToken 触发)

Source

fn shutdown(&self)

优雅关闭

Source

fn init_sort() -> i32

初始化排序(值越小越先执行,默认 10000)

Source

fn trait_impls() -> &'static [fn() -> TypeId]

返回此组件实现的 trait TypeId 列表

#[component(as_trait = ...)] 宏自动生成。 默认为空 — 不实现任何 trait。

Dyn Compatibility§

This trait is not dyn compatible.

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

Implementors§

Source§

impl Component for AppAllConfig

Source§

const SCOPE: Scope = Scope::Singleton

Source§

type Deps = ()

Source§

impl Component for LoggingInterceptor

Source§

const SCOPE: Scope = crate::Scope::Singleton

Source§

type Deps = ()

Source§

impl Component for MetricsInterceptor

Source§

const SCOPE: Scope = crate::Scope::Singleton

Source§

type Deps = ()