Dependency injection is a technique which is largely used to avoid tight coupling inside the applications, by abstracting objects/modules and inverting the dependency flow.

Of course this is a simplified explanation of it but, if you are here, I believe that we are familiarized with the technique and you might have googled “dependency injection in rust”, or something like that, in order to know specifically how to use it in Rust.

Otherwise, check this link out. The explanation about the topic is way more instructive =).

In this article I want to show how to use dependency injection using Waiter DI, a very useful DI crate for Rust.

Assuming that you have already installed Rust in your computer, select your workspace folder and run the following command:

cargo new di_poc --bin

A di_poc folder will be created. Open this folder inside of your preferred editor. I’m using VS Code.

The structure of the project is as follows:

Image for post

Project structure

Inside of src folder, the following folders were created:

  • abst: where I put the trait (abstract code).
  • implementation: where I put the implementation, the struct which depends on the abstract.
  • services: the struct where the implementation for the trait will be injected

#dependency-injection #design-patterns #rust

Dependency Injection in Rust using Waiter DI
9.95 GEEK