rust_dix/lib.rs
1//! rust-dix — Rust Dependency Injection Framework
2//!
3//! A dependency injection container for Rust inspired by
4//! Microsoft.Extensions.DependencyInjection (MEDI).
5//!
6//! # Quick start
7//!
8//! ```rust
9//! use rust_dix::*;
10//! use std::sync::Arc;
11//!
12//! // Trait-based interface (recommended)
13//! trait ILogger: Send + Sync {
14//! fn log(&self, msg: &str);
15//! }
16//!
17//! struct ConsoleLogger;
18//! impl ILogger for ConsoleLogger {
19//! fn log(&self, msg: &str) { println!("[LOG] {}", msg); }
20//! }
21//!
22//! // Register as trait interface
23//! let provider = ServiceCollection::new()
24//! .singleton::<dyn ILogger>(|_| Arc::new(ConsoleLogger))
25//! .build()
26//! .unwrap();
27//!
28//! // Resolve as trait
29//! let logger: Arc<dyn ILogger> = provider.get().unwrap();
30//! logger.log("Hello");
31//! ```
32//!
33//! # Keyed services (strategy pattern)
34//!
35//! ```rust
36//! use rust_dix::*;
37//! use std::sync::Arc;
38//!
39//! trait Strategy: Send + Sync { fn execute(&self) -> &'static str; }
40//!
41//! struct FastStrategy;
42//! impl Strategy for FastStrategy { fn execute(&self) -> &'static str { "fast" } }
43//!
44//! struct SafeStrategy;
45//! impl Strategy for SafeStrategy { fn execute(&self) -> &'static str { "safe" } }
46//!
47//! let provider = ServiceCollection::new()
48//! .keyed_singleton::<dyn Strategy>("fast", |_| Arc::new(FastStrategy))
49//! .keyed_singleton::<dyn Strategy>("safe", |_| Arc::new(SafeStrategy))
50//! .build()
51//! .unwrap();
52//!
53//! let fast: Arc<dyn Strategy> = provider.get_keyed("fast").unwrap();
54//! assert_eq!(fast.execute(), "fast");
55//! ```
56//!
57//! # Build-time validation
58//!
59//! rust-dix validates dependencies during `build()` to catch errors early:
60//!
61//! ```rust
62//! # use rust_dix::*;
63//! # use std::sync::Arc;
64//! # struct A;
65//! # struct B;
66//! // Circular dependency detection — factories resolve deps via `get_any`
67//! // (the `get::<T>()` method requires `Self: Sized` and cannot be called
68//! // on `&dyn IServiceResolver`).
69//! let result = ServiceCollection::new()
70//! .singleton(|r| {
71//! let _b = r.get_any(std::any::type_name::<B>()); // A depends on B
72//! Arc::new(A)
73//! })
74//! .singleton(|r| {
75//! let _a = r.get_any(std::any::type_name::<A>()); // B depends on A → CIRCULAR!
76//! Arc::new(B)
77//! })
78//! .build();
79//!
80//! assert!(result.is_err());
81//! if let Err(RdiError::CircularDependency(cycle)) = result {
82//! println!("Circular dependency detected: {}", cycle);
83//! }
84//! ```
85//!
86//! # Async support
87//!
88//! For services that require async initialization (e.g., database
89//! connections, remote config loading), use `build_async()` and
90//! the `async_*` registration methods. `build_async()` returns
91//! `Arc<ServiceProvider>` so that `provider_arc()` is available for
92//! async resolution:
93//!
94//! ```rust,ignore
95//! use rust_dix::*;
96//! use std::sync::Arc;
97//!
98//! struct DbPool { conn: String }
99//!
100//! async fn connect_to_db() -> DbPool {
101//! // async connection setup...
102//! DbPool { conn: "connected".into() }
103//! }
104//!
105//! # async fn run() {
106//! let provider = ServiceCollection::new()
107//! .async_singleton(|_| Box::pin(async {
108//! Arc::new(connect_to_db().await)
109//! }))
110//! .build_async()
111//! .await
112//! .unwrap();
113//!
114//! let pool: Arc<DbPool> = provider.get_async().await.unwrap();
115//! # }
116//! ```
117//!
118//! # Features
119//!
120//! - **Three lifetimes**: Singleton, Scoped, Transient
121//! - **Keyed services**: multiple implementations of the same trait by key
122//! - `keyed_singleton(key, factory)` — shared globally
123//! - `keyed_scoped(key, factory)` — shared within scope
124//! - `keyed_transient(key, factory)` — new instance each time
125//! - **Constructor injection**: `#[derive(Inject)]` on structs
126//! - **Attribute-based auto-registration**: `#[rust_dix::inject]` on structs or trait impls
127//! - **Compile-time module scanning**: `#[rust_dix::module]` collects `register!()` declarations
128//! - **Cross-DLL support**: named service registry for cdylib plugins
129//! - **Layered containers**: child-first resolution via `ServiceProviderWrapper`
130//! - **Build-time validation**: circular dependency detection during `build()`
131//! - **Scope validation**: scoped services cannot be resolved from the root
132//! provider by default (MEDI `ValidateScopes` parity; opt out with
133//! [`ServiceProviderOptions::lenient`])
134//! - **Deterministic lifecycle**: eager singletons are created in registration
135//! order; [`ServiceProvider::dispose`] / [`Scope::dispose`] release cached
136//! instances in reverse creation order
137//! - **MEDI registration semantics**: the last registration wins for a single
138//! service; `get_all` returns unkeyed implementations in registration order
139//! (`get_all_keyed` for keyed ones)
140//!
141//! # Crate layout
142//!
143//! | Module | Description |
144//! |--------|-------------|
145//! | [`ServiceCollection`] | Register services with a builder API |
146//! | [`ServiceProvider`] | The root DI container |
147//! | [`Scope`] / [`ServiceScope`] | Scoped container (one per scope) |
148//! | [`IServiceResolver`] | Resolution trait (implemented by `ServiceProvider` & `Scope`) |
149//! | [`ServiceProviderWrapper`] | Child-first layered container |
150//! | [`ServiceLifetime`] | Enum: Singleton, Scoped, Transient |
151//! | [`IProvider`] | Unified trait for resolution + named registry |
152//! | [`RdiError`] | Error types (includes `CircularDependency`) |
153//!
154//! # Proc-macros
155//!
156//! - `#[derive(Inject)]` — auto-generates constructor injection code
157//! - `#[rust_dix::inject]` — auto-registration on structs or trait impls
158//! - `#[rust_dix::module]` — compile-time module scanning
159//! - `rust_dix::register!(...)` — declare services inside `#[rust_dix::module]`
160
161pub mod bridge;
162mod cache;
163pub mod collection;
164pub mod entry;
165pub mod error;
166#[doc(hidden)]
167pub mod macros_support;
168pub mod provider;
169pub mod registration;
170pub mod scope;
171mod validation;
172pub mod wrapper;
173
174// ── Core types (MEDI-inspired naming) ──
175
176/// Service collection — register services, then call `.build()`.
177///
178/// Analogous to `IServiceCollection` in Microsoft.Extensions.DependencyInjection.
179pub use collection::ServiceCollection;
180
181/// Built service provider — the root DI container (read-only after build).
182///
183/// 兼具 MEDI 中 `IServiceProvider` 与 root scope 双重身份:
184/// - 作为 `IServiceProvider`:提供类型/键控/命名解析入口。
185/// - 作为 root scope:**默认启用严格 scope 校验**(对齐 MEDI/ASP.NET Core 开发环境的
186/// `ValidateScopes`),从根解析 Scoped 服务返回 [`RdiError::ScopedFromRootProvider`];
187/// 在 [`ServiceProvider::scope`] 创建的 Scope 内解析则正常缓存复用。若确实需要
188/// 0.7 的"根 scope 内单例化"行为,可用
189/// [`ServiceProviderOptions::lenient`] + [`ServiceCollection::build_with`]。
190/// - 与 MEDI 对齐,容器自身可作为内建服务解析:`provider.get::<ServiceProvider>()`
191/// 与 `#[inject] Arc<ServiceProvider>`(或专用 `#[inject(provider)]`)均可用,
192/// eager singleton 与懒解析服务一致。
193/// - [`ServiceProvider::dispose`] 按创建逆序释放 singleton / root-scoped 实例并
194/// 标记容器不可用(后续解析返回 [`RdiError::ProviderDisposed`])。
195/// - ⚠️ singleton 持有 `Arc<ServiceProvider>` 会形成 `容器 → singleton → 容器` 的
196/// 强引用环,容器不再可能被回收;需要按任务创建 scope 的 singleton 应优先注入
197/// [`ScopeFactory`](内置实现为弱引用,无环)。构造函数内也不要通过注入的
198/// provider 解析服务(会被拒绝),请保存句柄并在方法中延迟解析。
199///
200/// Analogous to `IServiceProvider` in MEDI.
201pub use provider::ServiceProvider;
202
203/// Options for [`ServiceCollection::build_with`] /
204/// [`ServiceCollection::build_async_with`].
205///
206/// Defaults match MEDI/ASP.NET Core development-time scope validation:
207/// `validate_scopes = true`. Use [`ServiceProviderOptions::lenient`] to allow
208/// resolving scoped services from the root provider (pre-0.8 behavior).
209pub use provider::ServiceProviderOptions;
210
211/// Service descriptor containing registration metadata.
212pub use entry::ServiceDescriptor;
213
214/// Service lifetime enum: [`Singleton`](ServiceLifetime::Singleton),
215/// [`Scoped`](ServiceLifetime::Scoped), [`Transient`](ServiceLifetime::Transient).
216pub use entry::ServiceLifetime;
217
218/// Core resolution trait. Both [`ServiceProvider`] and [`Scope`] implement this.
219pub use entry::IServiceResolver;
220
221/// A scoped service provider — created via [`ServiceProvider::scope`].
222///
223/// Analogous to `IServiceScope` in MEDI.
224pub use scope::Scope;
225
226/// Alias for [`Scope`] with MEDI-inspired naming (`IServiceScope`).
227pub use scope::Scope as ServiceScope;
228
229/// Factory trait for creating independent scopes.
230///
231/// The built provider always offers an implementation (no manual registration
232/// required): `provider.get::<dyn ScopeFactory>()` and
233/// `#[inject] Arc<dyn ScopeFactory>` fields both work, including inside
234/// eagerly built singletons (e.g. background workers that need one scope per
235/// tick). Explicit `singleton::<dyn ScopeFactory>(...)` registrations take
236/// precedence.
237///
238/// The built-in implementation holds a `Weak` reference to the container, so a
239/// singleton may store it without creating an `Arc` cycle; the container must
240/// therefore outlive services created from it.
241pub use scope::ScopeFactory;
242
243/// Internal types used by the container.
244pub use entry::{ServiceEntry, ServiceFactory};
245
246/// Wrapper combining child + root provider with child-first resolution.
247pub use wrapper::ServiceProviderWrapper;
248
249// ── Plugin / cross-DLL support ──
250
251/// Unified trait for service resolution and named registry access.
252pub use bridge::IProvider;
253
254// ── Error types ──
255
256/// Error types returned from service resolution.
257pub use error::{inject_arc, RdiError};
258
259// ── Runtime registration ──
260
261pub use registration::ServiceRegistration;
262
263/// Re-export of `inventory` so that `#[rust_dix::inject]` generated code
264/// can call `rust_dix::inventory::submit!` without requiring downstream crates
265/// to add `inventory` to their own `Cargo.toml`.
266#[doc(hidden)]
267pub use inventory;
268
269// ── Proc-macros ──
270
271// `inject` is the attribute macro (placed on structs or trait impls).
272// `register` is the function-like macro used inside `#[rust_dix::module]`.
273pub use rust_dix_macros::{inject, module, register, Inject};