Introduction
Dependency Injection (DI) is one of the most important concepts in modern .NET development. In .NET 8, DI is built-in and widely used in ASP.NET Core applications to create clean, maintainable, and testable code.
In simple terms, Dependency Injection means providing the required dependencies (services, objects, or classes) to a class rather than creating them within the class.
This helps reduce tight coupling, improves code flexibility, and makes applications easier to scale and test.
In this article, we will understand how Dependency Injection works in .NET 8, its types, and how to implement it step by step with practical examples.
What is Dependency Injection in .NET 8?
Dependency Injection is a design pattern used to achieve Inversion of Control (IoC).
Instead of a class creating its own dependencies, those dependencies are injected from outside.
Without Dependency Injection (Tightly Coupled Code)
public class EmailService
{
public void SendEmail(string message)
{
Console.WriteLine("Email sent: " + message);
}
}
public class Notification
{
private EmailService _emailService = new EmailService();
public void Notify()
{
_emailService.SendEmail("Hello User");
}
}
Problem
Tight coupling between classes
Hard to test
Difficult to replace implementation
With Dependency Injection (Loosely Coupled Code)
public interface IEmailService
{
void SendEmail(string message);
}
public class EmailService : IEmailService
{
public void SendEmail(string message)
{
Console.WriteLine("Email sent: " + message);
}
}
public class Notification
{
private readonly IEmailService _emailService;
public Notification(IEmailService emailService)
{
_emailService = emailService;
}
public void Notify()
{
_emailService.SendEmail("Hello User");
}
}
Now the dependency is injected, not created inside the class.
Types of Dependency Injection in .NET 8
1. Constructor Injection (Most Common)
Dependencies are provided through the constructor.
public class UserService
{
private readonly IEmailService _emailService;
public UserService(IEmailService emailService)
{
_emailService = emailService;
}
}
2. Method Injection
Dependencies are passed as method parameters.
public void Process(IEmailService emailService)
{
emailService.SendEmail("Processing...");
}
3. Property Injection (Less Common)
Dependencies are set via properties.
public IEmailService EmailService { get; set; }
Built-in Dependency Injection in .NET 8
.NET 8 provides a built-in IoC container using IServiceCollection.
You typically configure services in Program.cs.
Step-by-Step: Implement Dependency Injection in .NET 8
Step 1: Create Interface
public interface IMessageService
{
string GetMessage();
}
Join the conversation! Your thoughts help the community grow.