Rust
Mar 25, 2025
5 Min. Read
How To Do Dependency Injection In Rust With Static Dispatching
Dependency injection (DI) is a common design pattern that tech companies use to increase the flexibility, maintainability, and testability of their software. Long-standing, industry-standard languages such as Java have a number of frameworks solely for this purpose, such as Spring, Guice, and Dagger.
However, in Rust, dependency injection is not an easy pattern to implement, at least not in a "Rust-like" way. Most, if not all, libraries and examples achieve DI through dynamic dispatching (trait objects). They also typically do not offer a solution for, in my opinion, one of the best features of DI frameworks - the ability to configure environment-specific dependencies at compile time (i.e. production dependencies for prod environments, beta dependencies for beta environments).