Introduction
Dependency Injection (DI) is one of the most important concepts in modern .NET development, especially when building scalable applications like ASP.NET Core APIs, Microservices, or Enterprise applications.
What is Dependency Injection?
Dependency Injection is a design pattern in which an object receives its dependencies from outside rather than creating them itself.
In simple words:
❌ Without DI → Class creates its own dependency
✅ With DI → Dependency is provided to the class
Why Do We Need Dependency Injection?
Let’s understand with a real-life example.
Imagine:
A Car needs an Engine.
❌ Without DI
public class Car
{
private Engine _engine;
public Car()
{
_engine = new Engine(); // Tight coupling
}
public void Start()
{
_engine.Run();
}
}
Problems:
Tight coupling
Hard to test
Not flexible
Difficult to replace Engine
✅ With Dependency Injection
public class Car
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine;
}
public void Start()
{
_engine.Run();
}
}
Now the Engine is injected from outside.
This makes:
Code loosely coupled
Easy to test
Easy to replace implementation
Important Terms
1️⃣ Dependency
A class that another class needs.
Example:
Car depends on Engine.
2️⃣ Inversion of Control (IoC)
Instead of the class controlling dependencies, control is given to the container.
3️⃣ IoC Container
Framework component that manages dependencies.
In .NET → Built-in DI container
Types of Dependency Injection
1️⃣ Constructor Injection (Most Common)
Dependency is passed through the constructor.
public class UserService
{
private readonly IEmailService _emailService;
public UserService(IEmailService emailService)
{
_emailService = emailService;
}
}
✔ Recommended approach
2️⃣ Property Injection
public IEmailService EmailService { get; set; }
Less used in .NET Core.
3️⃣ Method Injection
public void SendEmail(IEmailService emailService)
{
emailService.Send();
}
Dependency Injection in ASP.NET Core (Real Example)
Let’s create a simple example.
Step 1: Create Interface
public interface IMessageService
{
string GetMessage();
}
Step 2: Create Implementation
public class MessageService : IMessageService
{
public string GetMessage()
{
return "Hello from Dependency Injection!";
}
}

Join the conversation! Your thoughts help the community grow.