Skip to main content

What is Dependency Injection?

Dependency Injection (DI) is a design pattern where an object receives its dependencies from an external source instead of creating them itself. A dependency is any object another object requires to perform its work. Examples:
  • Database
  • Repository
  • Logger
  • Email Service
  • Configuration

Without Dependency Injection

The object creates its own dependency.
Problems
  • Tight coupling
  • Hard to test
  • Difficult to replace dependencies

With Dependency Injection

The dependency is supplied from outside.
Usage:
Now Car only uses the engine—it doesn’t create it.

Real-world Example: Repository & Service

Without DI

With DI

Usage:
Later, we can replace the repository without changing the service.

Benefits

  • Loose coupling
  • Easier testing
  • Better maintainability
  • Easily replace implementations
  • More reusable code

Types of Dependency Injection

Constructor Injection (Most Common)

Setter Injection

Method Injection

FastAPI Example

FastAPI automatically performs dependency injection.
A more realistic example using a service:

Summary

Dependency Injection is a technique where:
  • Objects receive their dependencies instead of creating them.
  • Components remain loosely coupled.
  • Dependencies can be replaced easily.
  • Testing becomes much simpler.
  • Frameworks like FastAPI, Spring Boot, and ASP.NET Core automate dependency injection.