Function runtime_injector_actix::constant[][src]

pub fn constant<T>(value: T) -> ConstantProvider<T> where
    T: Service

Create a provider from a constant value. While the service itself will never be exposed through a mutable reference, if it supports interior mutability, its fields still can be mutated. Since the provider created with this function doesn’t recreate the value each time it’s requested, state can be stored in this manner.

Example

use runtime_injector::{constant, Injector, Svc};

let mut builder = Injector::builder();
builder.provide(constant(8i32));

let injector = builder.build();
let value: Svc<i32> = injector.get().unwrap();

assert_eq!(8, *value);

Interior mutability

One use case for constant values is to create a mutex to lock static, synchronized values that can be accessed from any service. For instance, suppose you wanted to create a counter to keep track of how many instances of a service you created:

use runtime_injector::{constant, Injector, IntoTransient, Svc};
use std::sync::Mutex;

struct Foo;
impl Foo {
    pub fn new(counter: Svc<Mutex<i32>>) -> Self {
        let mut counter = counter.lock().unwrap();
        *counter += 1;
        Foo
    }
}

let mut builder = Injector::builder();
builder.provide(Foo::new.transient());
builder.provide(constant(Mutex::new(0i32)));

let injector = builder.build();
let foo: Svc<Foo> = injector.get().unwrap();
let value: Svc<Mutex<i32>> = injector.get().unwrap();

assert_eq!(1, *value.lock().unwrap());