Dependency Injection in ASP.NET Core Explained with Real-World Examples
Dependency Injection (DI) is one of the fundamental concepts in modern ASP.NET Core development. It helps developers build applications that are easier to maintain, test, extend, and scale.
If you've worked with ASP.NET Core, you've probably seen code like this:
builder.Services.AddScoped<IProductService, ProductService>();
But what exactly does it do? Why do we use interfaces? What is the difference between AddScoped, AddTransient, and AddSingleton?
In this article, we'll explore Dependency Injection from the ground up and understand how to use it in real-world ASP.NET Core applications.
What Is Dependency Injection?
Dependency Injection is a design pattern in which a class receives the objects or services it depends on from an external source instead of creating those dependencies itself.
Consider a simple example.
public class OrderController
{
private readonly OrderService _orderService;
public OrderController()
{
_orderService = new OrderService();
}
}
Here, the OrderController is directly responsible for creating its OrderService.
This creates tight coupling between the two classes. If we later change the implementation of OrderService, modify its constructor, or want to replace it with another service, we may need to modify the controller.
A better approach is to let ASP.NET Core provide the dependency.
public class OrderController
{
private readonly IOrderService _orderService;
public OrderController(IOrderService orderService)
{
_orderService = orderService;
}
}
Now the controller doesn't need to know how the service is created. It only needs to know that an implementation of IOrderService is available.
This is Dependency Injection.
Why Do We Use Dependency Injection?
Dependency Injection provides several important benefits.
1. Loose Coupling
Classes depend on abstractions rather than concrete implementations.
This makes it easier to replace services without changing the classes that consume them.
2. Easier Unit Testing
Dependencies can be replaced with mock implementations during testing.
Instead of connecting to an actual database, we can inject a mocked service and test the controller's behavior independently.
3. Better Maintainability
Business logic can be separated into services, repositories, and other components.
Each class becomes responsible for a smaller, more focused task.
4. Centralized Object Management
ASP.NET Core manages service creation, dependency resolution, and disposal based on the configured lifetime.
This reduces the need to manually create and manage objects throughout the application.
Understanding the Three Service Lifetimes
ASP.NET Core provides three commonly used service registration lifetimes:
- Transient
- Scoped
- Singleton
Understanding these lifetimes is critical because choosing the wrong one can lead to unexpected behavior, memory issues, or concurrency problems.
1. Transient
Transient services are created every time they are requested from the dependency injection container.
builder.Services.AddTransient<IEmailService, EmailService>();
Whenever the application requests IEmailService, a new instance is created.
When should you use Transient?
Transient services are suitable for lightweight, stateless services that don't need to maintain state between requests or operations.
Examples include:
- Utility services
- Formatting services
- Lightweight business logic services
- Stateless helper components
2. Scoped
Scoped services are created once per dependency injection scope.
In a typical ASP.NET Core web application, a scope is created for each HTTP request.
builder.Services.AddScoped<IProductService, ProductService>();
If multiple components within the same HTTP request depend on IProductService, they generally receive the same instance.
A new instance is created for the next HTTP request.
When should you use Scoped?
Scoped is commonly used for:
- Business services
- Entity Framework Core DbContext
- Repository services
- Request-specific processing
For most application services that interact with a database through EF Core, Scoped is usually the appropriate lifetime.
3. Singleton
Singleton services are created once and reused for the lifetime of the application.
builder.Services.AddSingleton<IApplicationSettings, ApplicationSettings>();
Every consumer receives the same instance.
When should you use Singleton?
Singleton services are appropriate for services that:
- Are thread-safe
- Maintain shared application-wide state when designed for it
- Are expensive to initialize
- Don't depend on request-specific services
Examples include carefully designed application-wide caches or services that manage shared resources.
Important: Singleton services must be thread-safe because multiple requests may access the same instance simultaneously.
Comparing Service Lifetimes
LifetimeInstance CreationTypical UseTransientEvery resolutionLightweight stateless servicesScopedOnce per request scopeBusiness services, DbContextSingletonOnce per applicationShared thread-safe services
Building a Real-World Example
Let's create a simple product service using Dependency Injection.
Step 1: Create the Interface
public interface IProductService
{
Task<List<Product>> GetAllAsync();
Task<Product?> GetByIdAsync(int id);
}
The interface defines what the service can do without exposing its implementation details.
Step 2: Implement the Service
public class ProductService : IProductService
{
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
{
_context = context;
}
public async Task<List<Product>> GetAllAsync()
{
return await _context.Products
.ToListAsync();
}
public async Task<Product?> GetByIdAsync(int id)
{
return await _context.Products
.FirstOrDefaultAsync(p => p.Id == id);
}
}
The service contains the business logic and database operations related to products.
Notice that the AppDbContext is also injected rather than created manually.
Step 3: Register the Service
In Program.cs:
builder.Services.AddScoped<IProductService, ProductService>();
This tells ASP.NET Core:
Whenever a component requests IProductService, provide an instance of ProductService using the Scoped lifetime.
Step 4: Inject the Service into a Controller
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly IProductService _productService;
public ProductsController(IProductService productService)
{
_productService = productService;
}
[HttpGet]
public async Task<IActionResult> GetAll()
{
var products = await _productService.GetAllAsync();
return Ok(products);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
var product = await _productService.GetByIdAsync(id);
if (product == null)
return NotFound();
return Ok(product);
}
}
The controller doesn't know how products are retrieved. It delegates that responsibility to the service.
This separation makes the application easier to maintain and test.
What Happens Behind the Scenes?
When ASP.NET Core receives an HTTP request, it creates the necessary request scope and resolves the controller's dependencies.
For example:
HTTP Request
|
v
ProductsController
|
v
IProductService
|
v
ProductService
|
v
AppDbContext
|
v
Database
The dependency injection container builds the dependency chain automatically.
When the request finishes, scoped services are disposed of appropriately.
This is particularly important when using Entity Framework Core because DbContext is designed to be used as a short-lived unit of work.
A Common Mistake: Injecting Scoped Services into Singleton Services
Consider the following example:
builder.Services.AddScoped<AppDbContext>(); builder.Services.AddSingleton<ReportService>();
If ReportService depends directly on AppDbContext, this can cause a lifetime mismatch because a Singleton service lives for the lifetime of the application while the DbContext is scoped.
A Singleton must not directly capture a scoped service in its constructor.
For example, this is problematic:
public class ReportService
{
private readonly AppDbContext _context;
public ReportService(AppDbContext context)
{
_context = context;
}
}
If ReportService is registered as Singleton, it may effectively hold onto a scoped dependency for far too long.
This can lead to incorrect behavior, concurrency issues, or runtime errors when scope validation is enabled.
How to fix it
The simplest solution is often to change the service lifetime to Scoped:
builder.Services.AddScoped<ReportService>();
If a Singleton genuinely needs to perform scoped work, use IServiceScopeFactory to create an explicit scope when needed, rather than holding a scoped dependency directly.
Dependency Injection and Clean Architecture
Dependency Injection becomes even more useful as an application grows.
A well-organized ASP.NET Core application might contain:
MyApplication │ ├── Controllers │ ├── Services │ ├── Interfaces │ │ └── IProductService.cs │ └── ProductService.cs │ ├── Repositories │ ├── Models │ ├── DTOs │ ├── Data │ └── AppDbContext.cs │ └── Program.cs
The controller handles HTTP requests, the service handles business logic, and the data access layer handles persistence.
Dependency Injection connects these components without forcing them to know how each dependency is created.
This approach makes larger applications easier to extend and reduces unnecessary coupling between layers.
Final Thoughts
Dependency Injection is more than just a way to register services in program.cs. It is an architectural practice that helps developers build flexible and maintainable applications.
By understanding how DI works and choosing the correct service lifetime, you can avoid common architectural mistakes and create applications that are easier to test, scale, and evolve.
When building ASP.NET Core applications, start by separating responsibilities, depend on abstractions where they provide value, and let the framework manage your services.
Once you understand Dependency Injection properly, many other ASP.NET Core features, including middleware, logging, configuration, database access, and background services, become much easier to understand.
Happy coding!