Dependency Injection (DI) in ASP.NET Core is a technique to achieve loose coupling between classes and their dependencies. Instead of creating objects manually, the framework injects required services at runtime. DI makes applications modular, testable, and maintainable.
Key Features:
- Promotes loose coupling and modular design
- Built-in support in ASP.NET Core
- Supports Transient, Scoped, and Singleton lifetimes
- Simplifies unit testing
- Works with custom and framework services
Example:
Define a service interface and implementation:
public interface IMessageService
{
string GetMessage();
}
public class MessageService : IMessageService
{
public string GetMessage() => "Hello Dependency Injection!";
}
Register and use the service in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IMessageService, MessageService>();
var app = builder.Build();
app.MapGet("/", (IMessageService msgService) => msgService.GetMessage());
app.Run();
Dependency Injection is a core part of ASP.NET Core that simplifies service management and enhances code quality.
Citations: