hamsterbyte

Understanding Dependency Injection in C#

Dependency Injection (DI) is a fundamental design pattern in modern C# development. It promotes loose coupling and makes your code more testable and maintainable.

What is Dependency Injection?

Instead of a class creating its dependencies, they are provided (injected) from the outside. This inverts the control of dependency creation, following the Inversion of Control (IoC) principle.

Types of Injection

public class OrderService
{
    private readonly IEmailService _emailService;
    
    public OrderService(IEmailService emailService)
    {
        _emailService = emailService;
    }
}

Property Injection

public class OrderService
{
    public IEmailService EmailService { get; set; }
}

Service Lifetimes

.NET Core provides three service lifetimes:

services.AddTransient<IEmailService, EmailService>();
services.AddScoped<IOrderService, OrderService>();
services.AddSingleton<IConfiguration, Configuration>();

Benefits

  1. Easier unit testing with mock dependencies
  2. Loose coupling between components
  3. Better separation of concerns
  4. More maintainable code

Start using DI in your projects to build more robust and testable applications!

Tags: