Compile-time dependency injection in Rust (no dyn, no Arc, no runtime container)

⚓ Rust    📅 2026-04-05    👤 surdeus    👁️ 7      

surdeus

At some scale, composition becomes the harder problem in Rust applications, not memory safety or performance.

In ecosystems like Java, this is typically addressed with dependency injection frameworks, but those rely heavily on runtime mechanisms (reflection, containers, dynamic resolution), which don’t map well to Rust.

I’ve been exploring a different direction:

Can dependency injection be done entirely at compile time?

The approach I ended up with is based on:

  • traits as capability contracts
  • “use-traits” to express dependencies
  • generics + monomorphization for wiring
  • macros to reduce boilerplate

The goal is to keep everything:

  • fully type-checked at compile time
  • no runtime container
  • no dyn in the core path
  • no Arc/Rc required for composition

The code is a bit too large to include here, so I’ve put everything into a small repo:

And a longer explanation here (might be easier to follow than the code alone):
https://medium.com/@amid.ukr/can-rust-have-zero-cost-dependency-injection-fc0c9ae6abd3


I’d really appreciate feedback on a couple of things:

  1. Does this approach make sense in Rust, or does it feel like it goes against idiomatic patterns?
  2. Am I solving a real problem here, or is this overengineering?
  3. Are there existing patterns/crates that address this in a simpler or more “Rusty” way?

Also, since I’ve already started working in this direction, I’m curious if there’s a meaningful way this could be useful for the community (as a library, pattern, or something else).

2 posts - 2 participants

Read full topic

🏷️ Rust_feed