Dependency injection in c# with an example

Kamlesh Singh
5 min readJun 5, 2023

Dependency injection (DI) is a design pattern commonly used in software development, particularly in object-oriented languages like C#. It promotes loose coupling and modularization by allowing objects to depend on abstractions rather than concrete implementations. This makes code more flexible, maintainable, and testable. In C#, you can implement dependency injection in various ways, such as constructor injection, property injection, or method injection.

  1. Constructor injection:
// Interface representing the dependency
public interface IMessageService
{
void SendMessage(string message);
}

// Concrete implementation of the dependency
public class EmailService : IMessageService
{
public void SendMessage(string message)
{
Console.WriteLine($"Sending email: {message}");
}
}

// Class that depends on the IMessageService
public class NotificationService
{
private readonly IMessageService _messageService;

// Constructor injection
public NotificationService(IMessageService messageService)
{
_messageService = messageService;
}

public void SendNotification(string message)
{
_messageService.SendMessage(message);
}
}

// Usage example
public class Program
{
public static void Main()
{
// Create an instance of the dependency
IMessageService emailService = new EmailService();

// Create an instance of the class with the dependency injected
NotificationService notificationService = new…

--

--

Kamlesh Singh
Kamlesh Singh

Written by Kamlesh Singh

Full Stack | Angular| .Net Core| SQL | Azure PaaS | AWS | Tech Lead

Responses (1)