Introduction
When building applications, we often create objects inside classes. But this creates tight coupling, making code hard to maintain.
ASP.NET Core solves this problem using Dependency Injection (DI).
Dependency Injection is one of the most important concepts in modern development.
In this article, you will learn:
What is Dependency Injection?
Dependency Injection means providing required objects (dependencies) from outside instead of creating them inside the class.
Without Dependency Injection ❌
public class StudentController
{
private StudentService service = new StudentService();
}
Problem
Tight coupling
Hard to test
Hard to maintain
With Dependency Injection ✔
public class StudentController
{
private readonly StudentService _service;
public StudentController(StudentService service)
{
_service = service;
}
}
Benefit
Loose coupling
Easy testing
Better structure
Types of Dependency Injection
ASP.NET Core supports 3 types:
1️⃣ Transient
builder.Services.AddTransient<StudentService>();
👉 New object every time
2️⃣ Scoped
builder.Services.AddScoped<StudentService>();
👉 One object per request
3️⃣ Singleton
builder.Services.AddSingleton<StudentService>();
👉 Same object for entire application
Step-by-Step Example
Step 1: Create Interface
public interface IStudentService
{
string GetStudentName();
}
Step 2: Create Service
public class StudentService : IStudentService
{
public string GetStudentName()
{
return "Abhay";
}
}
Step 3: Register Service
builder.Services.AddScoped<IStudentService, StudentService>();
Step 4: Use in Controller
public class HomeController : Controller
{
private readonly IStudentService _service;
public HomeController(IStudentService service)
{
_service = service;
}
public IActionResult Index()
{
var name = _service.GetStudentName();
return Content(name);
}
}
Output
Abhay
Real-World Example
Dependency Injection is used in:
Database services
Logging
API services
Authentication
Why Dependency Injection is Important?
When to Use Which Lifetime?
| Scenario | Use |
|---|
| Lightweight service | Transient |
| Database context | Scoped |
| Global service | Singleton |
Common Mistakes
Best Practice
Always use interfaces
Use Scoped for DB
Avoid tight coupling
Conclusion
Dependency Injection is a powerful concept in ASP.NET Core that helps build clean and maintainable applications.
In this article, we learned:
What DI is
Types of DI
Step-by-step example
Real-world usage