Skip to content
BENIBIX Learn

Dependency Injection

Development🏗️ ArchitectureDesign Patterns

Also known as DI, Inversion of Control, Constructor Injection

Code gets the parts it needs from outside. It does not make them itself.

Think of it like

Think of it like a chef handed their knives each morning. They do not forge their own.

Example

Lucy's OrderService needs an email sender. In the app she passes a real one. In tests she passes a fake that just records each email.

Why it matters

Code that makes its own database and email sender is hard to test. Code that is handed them is easy.

Definition

Dependency injection means code is given the things it needs. It does not make them itself. A thing it needs is called a dependency, like a database or an email sender. The code just asks for them, often through its constructor. Whoever creates it decides which real or fake ones to pass in. This makes code easy to test and to rewire.

Example code

javascript
class OrderService {
  constructor(mailer) { this.mailer = mailer; }
}
new OrderService(new SmtpMailer());  // the real app
new OrderService(new FakeMailer());  // a test
The service never picks its own mailer. It is handed one.

Common mistake

Pulling in a big framework for it on a small project. Passing things to a constructor is often all you need.

Key takeaways

  1. 1
    Handed, not made. Dependencies come in.
  2. 2
    Real or fake. The caller picks.
  3. 3
    Plain is fine. No framework needed.