Rust

DI

A dependency injection container: factories with declared dependencies, built once, resolved through parent containers.
Rust 427 lines (123 code)split
PartCodeCommentsBlankTotalFiles
Rust source123280244271
Rust tests3003331

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-di = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with DI, each a complete program you can copy and run.

A container builds the objects an application is made of, such as connections, clients and services, from factories that declare what they depend on. Ask the container for an id and it resolves the dependencies, builds the object once, and shares it with every later caller.

Register and resolve a dependency

A factory receives its dependencies, resolved, in the order it declared them.

Rust
use utopia_di::Container;

let container = Container::new();
container.set("host", &[], |_| Ok(String::from("db.internal")));
container.set("dsn", &["host"], |deps| Ok(format!("postgresql://{}:5432", deps.get::<String>(0)?)));

assert_eq!(*container.get::<String>("dsn")?, "postgresql://db.internal:5432");

Share one instance

The factory runs on the first get; every later get returns the same instance.

Rust
use std::sync::Arc;
use utopia_di::Container;

let container = Container::new();
container.set("pool", &[], |_| Ok(vec![String::from("connection")]));

let first = container.get::<Vec<String>>("pool")?;
let second = container.get::<Vec<String>>("pool")?;
assert!(Arc::ptr_eq(&first, &second));

Scope dependencies with a child container

A child container adds or overrides dependencies for one request or job, and resolves everything else through its parent, which keeps sharing what it built.

Rust
use std::sync::Arc;
use utopia_di::Container;

let app = Arc::new(Container::new());
app.set("config", &[], |_| Ok("production"));

let request = Container::with_parent(app.clone());
request.set("user", &["config"], |deps| Ok(format!("user@{}", deps.get::<&str>(0)?)));

assert_eq!(*request.get::<String>("user")?, "user@production");
assert!(request.has("config"));
assert!(!app.has("user"));

Handle a missing dependency

Resolving an id that no container defines fails with Error::NotFound.

Rust
use utopia_di::{Container, Error};

let container = Container::new();
let error = container.get_any("cache").unwrap_err();
assert_eq!(error, Error::NotFound("cache".into()));
assert_eq!(error.to_string(), "Dependency cache not found");

Reference#

A dependency injection container: register how to build each dependency and which dependencies it needs, then resolve it by id. Each dependency is built once per container and shared afterwards; a container falls back to its parent for ids it does not define.

Container::set registers a factory with the ids it depends on; the factory receives them, resolved, as Dependencies. Container::get builds the dependency on first use, caches it, and returns it as an Arc. A child container (Container::with_parent) overrides some ids and resolves the rest through its parent, which caches what it builds.

Rust
use utopia_di::Container;

let container = Container::new();
container.set("config", &[], |_| Ok(String::from("configValue")));
container.set("service", &["config"], |deps| Ok(format!("service:{}", deps.get::<String>(0)?)));

assert_eq!(*container.get::<String>("service")?, "service:configValue");

API#

What utopia_di exports at its root.