Skip to main content

Crate injectium_core

Crate injectium_core 

Source
Expand description

A minimal dependency-injection container for Rust.

Injectium provides a runtime DI container built around providers.

Providers can be closure-backed providers, shared values registered as Arc<T>, or explicit value providers created with cloned / copied.

§Quick Start

use injectium_core::{Container, container, copied};

// Build a container with providers
let c = container! {
    providers: [
        copied(42_u32),
        |c: &Container| format!("value is {}", c.get::<u32>()),
    ],
};

assert_eq!(c.get::<u32>(), 42);
assert_eq!(c.get::<String>(), "value is 42");

§Using #[derive(Injectable)]

The injectium crate (not this one) re-exports the #[derive(Injectable)] macro which automatically implements the Injectable trait for your structs:

use injectium::{Injectable, container};
use std::sync::Arc;

#[derive(Clone, Injectable)]
struct Db {
    conn: Arc<Connection>,
}

#[derive(Clone, Injectable)]
struct Config {
    url: String,
}

#[derive(Injectable)]
struct Service {
    db: Db,
    config: Config,
}

// At application startup:
let c = container! {
    providers: [
        Arc::new(Connection::new()),
        Config { url: "localhost".into() },
    ],
};

// Anywhere in your code, resolve a fully-constructed Service:
let svc = Service::from_container(&c);

§Validation

Call Container::validate at startup to ensure every #[derive(Injectable)] struct’s dependencies are actually registered:

let c = container! { /* ... */ };
c.validate(); // panics with a helpful message if something is missing

This catches misconfiguration immediately rather than failing on first use.

Re-exports§

pub use inventory;

Macros§

container
Declarative macro for building a container from providers.
declare_dependency
Declare that a type $ty must be present in the Container.

Structs§

CloneProvider
An explicit provider that clones a stored value on each request.
Container
A runtime dependency-injection container.
ContainerBuilder
A builder for Container.
CopyProvider
An explicit provider that copies a stored value on each request.
DeclaredDependency
A dependency declaration collected at link time via inventory.

Traits§

Injectable
Types that can construct themselves from a Container.
Provider
A source that can provide values from a Container.
SyncBounds

Functions§

cloned
Wraps a cloneable value as an explicit clone-on-read provider.
copied
Wraps a copyable value as an explicit copy-on-read provider.