#dependency-injection #provider #arc #value #run-time

injectium-core

Core implementation and utilities for injectium

6 releases (3 breaking)

Uses new Rust 2024

0.4.0 Mar 6, 2026
0.3.0 Mar 3, 2026
0.2.1 Mar 3, 2026
0.2.0 Feb 24, 2026
0.1.1 Feb 24, 2026

#122 in #dependency-injection


Used in 2 crates (via injectium)

MIT license

25KB
425 lines

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.


injectium-core

Crates.io Version docs.rs

Core dependency-injection container implementation for Rust.

Installation

cargo add injectium-core

Quick Start

use std::sync::Arc;

use injectium_core::{Container, container};

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

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

Documentation

See docs.rs for full API documentation.

License

MIT. Made with ❤️ by Ray

Dependencies

~18KB