Dependency Injection in .NET Core
Dependency Injection (DI) is a technique in .NET Core used to manage class dependencies efficiently.
Why Use Dependency Injection?
- Reduces tight coupling between components.
- Improves testability of code.
- Makes code more maintainable and scalable.
How Dependency Injection Works
DI in .NET Core follows three main steps:
- Register: Add services to the DI container.
- Resolve: Inject dependencies where needed.
- Use: The injected service is used in the application.
Example of Dependency Injection
1. Define an Interface
We first create an interface that defines the contract for a service.
public interface IMessageService
{
string GetMessage();
}
2. Implement the Interface
We create a class that implements this interface.
public class MessageService : IMessageService
{
public string GetMessage()
{
return "Hello from Dependency Injection!";
}
}
3. Register the Service in `Program.cs`
We register the service in the DI container using `AddScoped()`.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped(); // Register service
var app = builder.Build();
app.MapControllers();
app.Run();
4. Inject Service into Controller
We inject `IMessageService` into a controller.
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageService)
{
_messageService = messageService;
}
public IActionResult Index()
{
var message = _messageService.GetMessage();
return View((object)message);
}
}
5. Display Output in View (`Index.cshtml`)
The injected message is displayed in a Razor View.
@model string
<h1>Dependency Injection Example</h1>
<p>@Model</p>
Conclusion
Using Dependency Injection in .NET Core makes applications more modular, testable, and easier to maintain.