Dependency Injection (DI) is a design pattern used in C# (and other programming languages) to achieve loose coupling between objects and their dependencies. It allows an object to receive its dependencies from an external source rather than creating them internally.
Why Use Dependency Injection?
1. Loose Coupling – Reduces dependencies between objects, making the system more maintainable.
2. Improved Testability – Dependencies can be mocked easily for unit testing.
3. Better Code Reusability – Components are more modular and reusable.
4. Easier to Manage Dependencies – Centralized management of dependencies.
How Dependency Injection Works in C#?
In C#, DI is commonly implemented using the built-in dependency injection container (IServiceCollection and IServiceProvider) available in ASP.NET Core.
Types of Dependency Injection
1. Constructor Injection (Most common)
2. Property Injection
3. Method Injection
Example: Implementing Constructor Injection in C#
Step 1: Create an Interface
public interface IMessageService
{
void SendMessage(string message);
}
Step 2: Implement the Interface
public class EmailService : IMessageService
{
public void SendMessage(string message)
{
Console.WriteLine($”Email sent: {message}”);
}
}
Step 3: Inject Dependency via Constructor
public class Notification
{
private readonly IMessageService _messageService;
public Notification(IMessageService messageService)
{
_messageService = messageService;
}
public void Notify(string message)
{
_messageService.SendMessage(message);
}
}
Step 4: Configure Dependency Injection in ASP.NET Core
var serviceProvider = new ServiceCollection()
.AddSingleton<IMessageService, EmailService>() // Register dependency
.BuildServiceProvider();
var notification = new Notification(serviceProvider.GetService<IMessageService>());
notification.Notify(“Hello, Dependency Injection!”);
Built-in Dependency Injection in ASP.NET Core
In ASP.NET Core, you register dependencies in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IMessageService, EmailService>(); // Register DI
var app = builder.Build();
app.Run();
Then, in a Controller:
public class HomeController : Controller
{
private readonly IMessageService _messageService;
public HomeController(IMessageService messageService)
{
_messageService = messageService;
}
public IActionResult Index()
{
_messageService.SendMessage(“Hello from Controller!”);
return View();
}
}
Conclusion
Dependency Injection is a powerful pattern that makes C# applications more modular, maintainable, and testable. It is widely used in ASP.NET Core applications for managing dependencies efficiently.