Understanding Dependency Injection (DI) in .NET

What is Dependency Injection?

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.

  • Improves Testability: Dependencies can be mocked or swapped easily during testing.
  • Reduces Coupling: Classes are loosely coupled and easier to maintain or extend.
  • Centralized Configuration: All dependencies are managed in a single location.

Why Use Dependency Injection in .NET?

Dependency Injection is built into ASP.NET Core and simplifies the management of services in your application. It ensures better maintainability and scalability.


How to Implement Dependency Injection in .NET

Here’s a quick step-by-step guide:

1. Define an Interface


// Services/IGreetingService.cs
public interface IGreetingService
{
    string GetGreeting();
}

                

The IGreetingService interface defines the contract for a greeting service.

2. Implement the Service


// Services/GreetingService.cs
public class GreetingService : IGreetingService
{
    public string GetGreeting() => "Hello, Dependency Injection!";
}

                

The GreetingService class implements the interface.

3. Register the Service


// 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.

4. Inject the Service


// 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.

5. Use the Service in the Razor Page


// Pages/Index.cshtml
@page
@model IndexModel

@Model.GreetingMessage

The Razor page displays the message returned by the injected service.