The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .
Dependency Injection (DI) in ASP.NET Core is a core design pattern used to
decouple components, improve testability, and make your application
maintainable and scalable.
What is Dependency Injection?
Dependency Injection means:
Instead of a class creating its own dependencies, those dependencies are
provided (injected) from outside.
Without DI (Bad Practice)
public class ArticleService
{
private readonly SqlRepository _repo;
public ArticleService()
{
_repo = new SqlRepository(); // tightly coupled
}
}
Problems:
Hard to test
Hard to replace implementation
Tight coupling
With DI (Good Practice)
public class ArticleService
{
private readonly IRepository _repo;
public ArticleService(IRepository repo)
{
_repo = repo; // injected
}
}
Built-in DI in ASP.NET Core
Unlike old ASP.NET MVC, ASP.NET Core has DI built-in.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Dependency Injection (DI) in ASP.NET Core is a core design pattern used to decouple components, improve testability, and make your application maintainable and scalable.
What is Dependency Injection?
Dependency Injection means:
Without DI (Bad Practice)
Problems:
With DI (Good Practice)
Built-in DI in ASP.NET Core
Unlike old ASP.NET MVC, ASP.NET Core has DI built-in.
You configure it in:
Step 1: Register Services
Step 2: Use in Controller
ASP.NET Core automatically injects it.
Service Lifetimes (Very Important)
1. Transient
New instance every time
2. Scoped (Most used)
One instance per request
3. Singleton
One instance for entire app
Which one should YOU use?
Based on your project:
Why DI is Important (Real Benefits)
1. Loose Coupling
You can switch:
without changing business logic
2. Testability
You can inject mock:
3. Better Performance Control
With proper lifetime:
4. Clean Architecture
Supports: