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

With Dependency Injection ✔

public class StudentController
{
    private readonly StudentService _service;

    public StudentController(StudentService service)
    {
        _service = service;
    }
}

Benefit

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:

Why Dependency Injection is Important?

When to Use Which Lifetime?

ScenarioUse
Lightweight serviceTransient
Database contextScoped
Global serviceSingleton

Common Mistakes

Best Practice

Conclusion

Dependency Injection is a powerful concept in ASP.NET Core that helps build clean and maintainable applications.

In this article, we learned: