Rustyinject是Rust的編譯時依賴注入DI庫

banq發表於2024-06-16


依賴注入是一種用於實現IoC(控制反轉)的設計模式,允許以靈活和解耦的方式建立,儲存和檢索依賴項。這為DI提供了一個容器,可以:

  • 儲存單例例項並提供它們。
  • 提供單例的克隆例項。
  • 使用工廠方法建立例項。

使用
下面是一個如何使用DI容器的例子:

use rustyinject::{DependencyContainer, injector::{factories::ConstructorFactory, Injector}};

struct MyService {
    <font>// Some fields<i>
}

impl ConstructorFactory for MyService {
    type Dependencies<'a> = ();
// Specify your dependencies here.<i>

    fn build(dependencies: Self::Dependencies<'_>) -> Self {
        Self {
           
// Some fields<i>
        }
    }
}

let container = DependencyContainer::default()
    .with_constructor_factory::<MyService>();

let my_service: MyService = (&container).inject();


 

相關文章