ru-di 0.1.0

A simple and lightweight dependency injection container for Rust
Documentation
  • Coverage
  • 0%
    0 out of 10 items documented0 out of 9 items with examples
  • Size
  • Source code size: 9.66 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 476.25 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 9s Average build duration of successful builds.
  • all releases: 26s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • ipconfiger/ru-di
    1 0 1
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • ipconfiger

ru-di

A simple and lightweight dependency injection container for Rust.

Crates.io Documentation License

Features

  • Simple and lightweight
  • Thread-safe
  • Support for both transient and singleton services
  • No runtime overhead
  • Zero dependencies

Installation

Add this to your Cargo.toml:

[dependencies]
ru-di = "0.1"

Usage

Basic Usage

use ru_di::Di;

// Define your services
struct Database {
    port: u16,
}

struct AppService {
    db: Database,
}

// Register services
Di::register::<Database, _>(|_| Database { port: 3306 });
Di::register::<AppService, _>(|di| {
    let db = di._get::<Database>().unwrap();
    AppService { db: db.clone() }
});

// Get service instance
let app = Di::get::<AppService>().unwrap();
assert_eq!(app.db.port, 3306);

Singleton Services

use ru_di::Di;

#[derive(Debug, PartialEq)]
struct Configuration {
    port: u16,
}

// Register a singleton
Di::register_single(Configuration { port: 8080 });

// Get singleton instance
if let Some(mut config) = Di::get_single::<Configuration>() {
    let config = config.get_mut();
    assert_eq!(config.port, 8080);
    config.port = 8081;
}

// The change persists
if let Some(mut config) = Di::get_single::<Configuration>() {
    let config = config.get_mut();
    assert_eq!(config.port, 8081);
}

API Documentation

Registering Services

  • Di::register<T, F>(factory: F) - Register a transient service
  • Di::register_single<T>(instance: T) - Register a singleton service

Getting Services

  • Di::get<T>() -> Result<T, Box<dyn Error>> - Get a transient service instance
  • Di::get_single<T>() -> Option<SingleRef<T>> - Get a singleton service instance

Thread Safety

All operations are thread-safe. The container uses Arc, Mutex, and RwLock internally to ensure thread safety.

License

This project is licensed under the MIT License - see the LICENSE file for details.