What Is Dependency Injection?

Dependency injection is a technique where an object receives the other objects it depends on from the outside, rather than creating them itself internally.

Published October 7, 2026

Dependency injection (DI) means giving an object the things it needs (its dependencies) from the outside instead of letting it create them itself. It makes code easier to test and swap.

The concept

Without DI, a class does new Mailer() internally and is stuck with it. With DI, the mailer is passed in through the constructor, so a test can pass a fake.

DI containers (Laravel's service container, Spring, NestJS) construct and wire objects automatically from type hints.

Who creates the dependency?

injectsusesContainer / callercreates MailerOrderServicereceives itMailerreal or fake
The caller supplies it, so it can be replaced.

Practical examples

Hard-coded (bad)

class Orders { constructor() { this.mail = new SmtpMailer() } }

Injected (good)

class Orders { constructor(mail) { this.mail = mail } }
new Orders(new SmtpMailer())
new Orders({ send: () => {} })   // test double

Laravel auto-wiring

class OrderController {
  public function __construct(private Mailer $mailer) {}
}

Common mistakes

  • Creating dependencies with new inside business classes.
  • Injecting too many dependencies (a design smell).
  • Using a service locator everywhere instead of constructor injection.

Key takeaways

  • Pass dependencies in, do not construct them inside.
  • Improves testing and flexibility.
  • Constructor injection is the clearest form.

FAQ

DI vs IoC?

Inversion of Control is the principle; DI is a technique that implements it.

Do I need a container?

Not for small apps; manual wiring works.

More General articles