# Dependency Injection

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

**Field:** Software Development  
**Category:** Architecture  
**Also known as:** DI, Inversion of Control, Constructor Injection

## Think of it like

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

## 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

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.

## 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.

## Why it matters

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

## Common mistake

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

## Three principles

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

## Related terms

- [Coupling](https://learn.benibix.com/term/development/coupling)
- [Unit Test](https://learn.benibix.com/term/development/unit-test)
- [Hexagonal Architecture](https://learn.benibix.com/term/development/hexagonal-architecture)
- [SOLID Principles](https://learn.benibix.com/term/development/solid-principles)

---

Source: https://learn.benibix.com/term/development/dependency-injection
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
