20 releases

0.2.15 Jan 28, 2024
0.2.14 Jan 27, 2024
0.2.8 Nov 19, 2023
0.1.4 Mar 17, 2023
0.1.3 Jan 7, 2023

#1765 in Rust patterns

Download history 72/week @ 2023-11-14 4/week @ 2023-11-21 26/week @ 2024-01-16 23/week @ 2024-01-23 9/week @ 2024-02-13 259/week @ 2024-02-20 64/week @ 2024-02-27

332 downloads per month
Used in 2 crates

MIT/Apache

11KB
254 lines

PortalDI

PortalDI is a ergonomic, lightweight and compile-time dependency injection (DI) library for Rust.

Features

  • Ergonomic apis for DI.

    You can forcus on a target type in most cases without worrying about containers.

    Hoge::di().hello(); 
    
  • Natively async support.

    • Asynchronous component creation is enabled.
    AsyncHoge::di()
    .await
    .hello()
    
  • DRY support by proc-macros.

    Almost boiler codes can be generated by PortalDI's proc-macro.

    #[derive(DIPortal)]
    struct Hoge {
      foo: DI<Foo>,
      ...
    }
    
  • Wasm support.

    • In Wasm target, PortalDI compiles DI container as Rc compatible.

    • In non Wasm target, components and traits must be thread-safe (Sync + Send).

Example

use portaldi::*;

#[derive(DIPortal)]
struct Hoge {
    foo: DI<dyn FooI>,
    bar: DI<Bar>,
}
impl Hoge {
    fn say_hello(&self) {
        println!("hello hoge < {}, {}", self.foo.hello(), self.bar.hello())
    }
}

pub trait FooI: DITarget {
    fn hello(&self) -> &str;
}

#[derive(DIPortal)]
#[provide(FooI)]
struct Foo {}

impl FooI for Foo {
    fn hello(&self) -> &str {
        "hello foo"
    }
}

#[derive(DIPortal)]
struct Bar {}

impl Bar {
    fn hello(&self) -> &str {
        "hello bar"
    }
}

fn main() {
    Hoge::di().say_hello();
}


Guides

For detailed guides, see docs page

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


lib.rs:

Defines core functionalities.

Dependencies

~0.3–0.8MB
~19K SLoC