Dependency Injection (DI) in ASP.NET Core is a technique to achieve Inversion of Control by providing dependencies to classes instead of creating them directly. DI enhances modularity, testability, and maintainability of applications.
Key Features:
- Supports built-in DI container
- Manages service lifetimes: Singleton, Scoped, Transient
- Integrates with controllers, Razor Pages, and middleware
- Reduces tight coupling between classes
- Makes unit testing easier
Example:
Registering services in Program.cs:
builder.Services.AddTransient<IEmailService, EmailService>();
var app = builder.Build();
Injecting a service into a controller:
public class HomeController : Controller
{
private readonly IEmailService _emailService;
public HomeController(IEmailService emailService)
{
_emailService = emailService;
}
public IActionResult Index()
{
_emailService.SendEmail("hello@example.com", "Test");
return View();
}
}
Dependency Injection in ASP.NET Core promotes loose coupling and improves application design, making apps easier to maintain and test.
Citations: