Dependency Injection (DI) is a design pattern used to achieve *Inversion of Control (IoC)* in software development. Instead of a class creating its own dependencies, they are provided (injected) from the outside.
Dependency Injection is built into ASP.NET Core and simplifies the management of services in your application. It ensures better maintainability and scalability.
Here’s a quick step-by-step guide:
// Services/IGreetingService.cs
public interface IGreetingService
{
string GetGreeting();
}
The IGreetingService
interface defines the contract for a greeting service.
// Services/GreetingService.cs
public class GreetingService : IGreetingService
{
public string GetGreeting() => "Hello, Dependency Injection!";
}
The GreetingService
class implements the interface.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Register the service in the DI container
builder.Services.AddScoped<IGreetingService, GreetingService>();
var app = builder.Build();
app.Run();
The AddScoped
method registers the service in the Dependency Injection container. You
can also use AddSingleton
or AddTransient
depending on the service's
lifetime requirements.
// Pages/Index.cshtml.cs
using Microsoft.AspNetCore.Mvc.RazorPages;
public class IndexModel : PageModel
{
private readonly IGreetingService _greetingService;
public string GreetingMessage { get; private set; }
public IndexModel(IGreetingService greetingService)
{
_greetingService = greetingService;
}
public void OnGet()
{
GreetingMessage = _greetingService.GetGreeting();
}
}
The service is injected into the IndexModel
constructor and used in the
OnGet
method.
// Pages/Index.cshtml
@page
@model IndexModel
@Model.GreetingMessage
The Razor page displays the message returned by the injected service.