pub trait Inject:
Sized
+ Send
+ Sync {
// Required method
fn inject(container: &Container) -> Result<Self, Error>;
}Expand description
A trait that adds the ability to inject dependencies when resolving a type from the DI container
If it’s required to construct a struct from other dependencies, the Inject can be implemented manually
§Example
ⓘ
use volga::{
App,
error::Error,
di::{Dc, Inject, Container},
ok
};
#[derive(Default, Clone)]
struct ScopedService;
#[derive(Clone)]
struct TransientService {
service: ScopedService
}
impl Inject for TransientService {
fn inject(container: &Container) -> Result<Self, Error> {
let scoped_service = container
.resolve::<ScopedService>()?;
Ok(Self { service: scoped_service })
}
}
let mut app = App::new();
app.add_scoped::<ScopedService>();
app.add_transient::<TransientService>();
app.map_get("/route", |transient_service: Dc<TransientService>| async move {
let scoped = &transient_service.service;
// Do something with scoped and/or transient service
ok!()
});Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.