Rudi
English | 简体中文
Rudi - an out-of-the-box dependency injection framework for Rust.
use ;
// Register `fn(cx) -> A { A }` as the constructor for `A`
;
;
// Register `fn(cx) -> B { B::new(cx.resolve::<A>()) }` as the constructor for `B`
// Register `fn(cx) -> C { C::B(cx.resolve::<B>()) }` as the constructor for `C`
// Register `fn(cx) -> () { Run(cx.resolve::<B>(), cx.resolve::<C>()) }` as the constructor for `()`
Features
- Three scopes:
Singleton
,Transient
andSingleOwner
(example). - Async functions and async constructors.
- Attribute macros can be used on
struct
,enum
,impl block
andfunction
. - Manual and automatic registration (thanks to inventory).
- Easy binding of trait implementations and trait objects.
- Distinguishing different instances with types and names.
- Generics (but must be monomorphized and manually registered) (example).
- Conditional registration (example).
- References (only
Singleton
andSingleOwner
scope) (example).
More complex example
use ;
use ;
// Register `async fn(cx) -> i32 { 42 }` as the constructor for `i32`,
// and specify the name of the instance of this `i32` type as `"number"`.
async
// Register `async fn(cx) -> Foo { Foo { number: cx.resolve_with_name_async("number").await } }`
// as the constructor for `Foo`, and specify the name of the instance of this `Foo` type as `"foo"`.
;
// Register `async fn(cx) -> Bar { Bar::new(cx.resolve_with_name_async("foo").await).await }`
// as the constructor for `Bar`.
//
// Bind the implementation of the `Debug` trait and the trait object of the `Debug` trait,
// it will register `asycn fn(cx) -> Rc<dyn Debug> { Bar::into_debug(cx.resolve_async().await) }`
// as the constructor for `Rc<dyn Debug>`.
async
async
More examples can be found in the examples and tests directories.
Credits
- Koin: This project's API design and test cases were inspired by Koin.
- inventory: This project uses inventory to implement automatic registration, making Rust's automatic registration very simple.
Contributing
Thanks for your help improving the project! We are so happy to have you!
License
Licensed under either of
- Apache License, Version 2.0,(LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT) at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.