injectium-core 0.1.0

Core implementation and utilities for injectium
Documentation

A minimal, zero-dependency dependency-injection container for Rust.

Injectium provides a runtime DI container with two registration strategies:

  • Singletons – a single instance shared across all consumers.
  • Factories – a closure that produces a fresh instance on each request.

Quick Start

use injectium_core::{Container, container};

// Build a container with singletons and/or factories
let c = container! {
    singletons: [
        42_u32,
        String::from("hello"),
    ],
    providers: [
        |c| format!("value is {}", c.get::<u32>()),
    ],
};

// Retrieve a singleton
assert_eq!(*c.get::<u32>(), 42);

// Resolve a factory (produces a new value each time)
assert_eq!(c.resolve::<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! {
    singletons: [
        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.