anthill-di
Rust ioc system
The library is for deep tree of dependencies
Advantages:
- async constructors (parallel building)
- runtime injection
- runtime check dependency cycles
- 3 type life cycle (transient/singleton/scoped)
- 3 injection way (simple trait constructor, trait as interface for type with constructor, closure as constructor)
- extensible dependency injection logic
Deficiencies:
- runtime check dependency cycles take some time for synchronize
- async building take some time for synchronize
Warning
Library required Rust nightly for trait as interface (Unsize)
Little overview
- Register dependency + how construct type + lifecycle
automatically generate Component + LifecycleBuilder + fake Service as component to component
- Register addition Service component to implemented trait (maby later something else like closure buildings)
- Request dependency
validate link -> take first Service (or collection in future) -> call LifecycleBuilder by TypeId from Service -> LifecycleBuilder build Component as CycledInstance (empty/with Arc/with Weak) -> call Service with CycledInstance -> return Service
Example
```rust
use asynctrait::asynctrait;
use tokio::runtime::Runtime;
use asynctrait::asynctrait;
use anthill_di::{
Constructor,
types::BuildDependencyResult,
DependencyContext,
DependencyLifeCycle
};
struct TransientDependency {
pub str: String,
}
[async_trait]
impl Constructor for TransientDependency {
async fn ctor(: crate::DependencyContext) -> BuildDependencyResult {
Ok(Self { str: "test".tostring() })
}
}
trait GetStr: Sync + Send {
fn get(&self) -> String;
}
impl GetStr for TransientDependency {
fn get(&self) -> String {
self.str.clone()
}
}
[tokio::main]
fn main() {
let rootcontext = DependencyContext::newroot();
rootcontext.registertype::(DependencyLifeCycle::Transient).await.unwrap()
.map_as::().await.unwrap();
let dependency = root_context.resolve::<Box<dyn GetStr>>().await.unwrap();
assert_eq!(dependency.get(), "test".to_string());
}
```
More shared examples present in src/tests folder
Refs