Skip to main content

Inject

Trait Inject 

Source
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§

Source

fn inject(container: &Container) -> Result<Self, Error>

Constructs a type with dependencies

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.

Implementations on Foreign Types§

Source§

impl Inject for ()

Source§

impl<T1> Inject for (T1,)
where T1: Inject,

Source§

impl<T1, T2> Inject for (T1, T2)
where T1: Inject, T2: Inject,

Source§

impl<T1, T2, T3> Inject for (T1, T2, T3)
where T1: Inject, T2: Inject, T3: Inject,

Source§

impl<T1, T2, T3, T4> Inject for (T1, T2, T3, T4)
where T1: Inject, T2: Inject, T3: Inject, T4: Inject,

Source§

impl<T1, T2, T3, T4, T5> Inject for (T1, T2, T3, T4, T5)
where T1: Inject, T2: Inject, T3: Inject, T4: Inject, T5: Inject,

Source§

impl<T> Inject for Dc<T>
where T: Send + Sync + 'static,

Source§

fn inject(container: &Container) -> Result<Dc<T>, Error>

Implementors§