Introduction
Dependency Injection (DI) is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. In ASP.NET Core, DI is a fundamental part of the framework, making it easier to manage dependencies and improve the modularity, testability, and maintainability of your applications.
In this article, we will cover the three primary DI lifecycles: Singleton, Transient, and Scoped. We will demonstrate how to register and use these services in an ASP.NET Core Web API application.
Prerequisites
To follow along, you should have
- Basic knowledge of ASP.NET Core.
- .NET SDK installed on your machine.
Step 1. Create a New ASP.NET Core Web API Project
First, create a new ASP.NET Core Web API project.
dotnet new webapi -n DependencyInjectionDemo
cd DependencyInjectionDemo
Step 2. Define the Services
Create interfaces and their implementations for Singleton, Transient, and Scoped services.
Interfaces
Create a new folder called Services and add the following interfaces.
// File: Services/ISingletonService.cs
public interface ISingletonService
{
Guid GetOperationId();
}
// File: Services/ITransientService.cs
public interface ITransientService
{
Guid GetOperationId();
}
// File: Services/IScopedService.cs
public interface IScopedService
{
Guid GetOperationId();
}
Implementations: Implement these interfaces in a single class.
// File: Services/OperationService.cs
public class OperationService : ISingletonService, ITransientService, IScopedService
{
private readonly Guid _operationId;
public OperationService()
{
_operationId = Guid.NewGuid();
}
public Guid GetOperationId()
{
return _operationId;
}
}
Step 3. Register the Services
Register these services in the Startup.cs file within the ConfigureServices method.
// File: Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Register the services
services.AddSingleton<ISingletonService, OperationService>();
services.AddTransient<ITransientService, OperationService>();
services.AddScoped<IScopedService, OperationService>();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Join the conversation! Your thoughts help the community grow.