🚀 Dependency Injection in ASP.NET Core – A Complete Beginner-to-Pro Guide
If you’ve been working with ASP.NET Core, you’ve probably seen the term Dependency Injection (DI) everywhere. It’s one of the most powerful features of .NET Core — but also one of the most misundersto
🔹 What is Dependency Injection (DI)?
Dependency Injection is a design pattern that allows classes to get their dependencies (services, repositories, etc.) from the outside, instead of creating them directly.
👉 In simple words:
Instead of a class creating the objects it needs, ASP.NET Core provides them for you.
This makes your code:
✅ More testable
✅ More maintainable
✅ Less tightly coupled
🔹 Example Without Dependency Injection
public class ProductService
{
private readonly ProductRepository _repo;
public ProductService()
{
_repo = new ProductRepository(); // tightly coupled
}
public void GetProducts() => _repo.GetAll();
}
Here, ProductService directly creates a ProductRepository.
Problem? If tomorrow you switch to SqlProductRepository or ApiProductRepository, you’ll need to change the class.
🔹 Example With Dependency Injection
public class ProductService
{
private readonly IProductRepository _repo;
public ProductService(IProductRepository repo)
{
_repo = repo;
}
public void GetProducts() => _repo.GetAll();
}
Now, ProductService doesn’t care which repository you’re using.
ASP.NET Core injects the right one when the app runs.
🔹 Registering Services in ASP.NET Core
You register dependencies in the Program.cs (or Startup.cs in older versions).
builder.Services.AddScoped<IProductRepository, SqlProductRepository>();
builder.Services.AddScoped<ProductService>();
When ProductService is called, .NET Core automatically provides an instance of SqlProductRepository.
🔹 Service Lifetimes in DI
ASP.NET Core DI supports three lifetimes:
Transient → New instance every time (
AddTransient)Scoped → One instance per request (
AddScoped)Singleton → One instance for the entire application (
AddSingleton)
âš¡ Choosing the right one is crucial for performance and memory usage.
🔹 Why Dependency Injection Matters?
Makes unit testing easier with mocks.
Allows flexibility in swapping implementations.
Reduces tight coupling and improves maintainability.
Encourages clean architecture (SOLID principles).
✅ In short: Dependency Injection is not just a feature of ASP.NET Core; it’s the backbone of writing clean, scalable, and testable code.


