1 个不稳定版本
0.1.0 | 2023 年 5 月 9 日 |
---|
#9 in #injector
10KB
267 代码行
Jabba
为 Rust 的异步依赖注入 [WIP]
示例
trait TestTrait: Injectable<Error = Infallible> + Send {
fn value(&self) -> usize;
}
struct TestStruct {
value: usize,
}
impl TestTrait for TestStruct {
fn value(&self) -> usize {
self.value
}
}
impl Injectable for TestStruct {
type Error = Infallible;
async fn create(_: Injector) -> Result<Self, Self::Error> {
static COUNTER: AtomicUsize = AtomicUsize::new(42);
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Ok(TestStruct {
value: COUNTER.fetch_add(1, Ordering::SeqCst),
})
}
}
#[tokio::main]
async fn main() {
let injector = Injector::new();
injector.bind::<dyn TestTrait, TestStruct>().await;
let instance = injector.get::<dyn TestTrait>().await.unwrap();
println!("instance value: {}", instance1.value());
}
依赖项
~0.6–1MB
~23K SLoC