Dependency Inversion Principle (DIP) - SOLID Principles in c#

Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions.

Instead of concrete classes, classes should depend on interfaces or abstract classes. This loose couples/ decouples classes for simpler testing and maintenance. 

public interface ILogger
{
   void Log(string message);
}

public class ConsoleLogger : ILogger
{
   public void Log(string message)
   {
       Console.WriteLine(message);
   }
}

public class EmailLogger : ILogger
{
   public void Log(string message)
   {
       // Send email
   }
}

 

public class Logger
{
   private readonly ILogger _logger;

   public Logger(ILogger logger)
   {
       _logger = logger;
   }

   public void Log(string message)
   {
       _logger.Log(message);
   }
}


This Principle emphasises creating software modules to reduce coupling, increase flexibility, scalability, and maintainability.


  • Abstractions: ILogger is an abstraction (an interface) that defines a contract for logging.
  • Implementations depend on Abstraction: Both ConsoleLogger and EmailLogger are low-level modules (specific implementations) that depend on the ILogger abstraction by implementing it.
  • High-level modules: If a high-level module (e.g., a service or a business logic class) needs to perform logging, it should depend on the ILogger interface, not directly on ConsoleLogger or EmailLogger (the concrete classes)

 

 


Scenarios Where Dependency Inversion Would Fail
showing how a high-level module might incorrectly depend on the concrete implementations:

public class UserService
{
   private ConsoleLogger _logger; // High-level module depends on a concrete implementation

   public UserService()
   {
       _logger = new ConsoleLogger();
   }

   public void CreateUser(string userName)
   {
       // ... user creation logic ...
       _logger.Log($"User '{userName}' created.");
   }
}

 

 

Abstraction makes switching loggers easy without altering the Logger class.

Author
Full Stack Developer

Deepak Talwar

Technical Architect & Full Stack Developer with 18+ years of Professional Experience in Microsoft Technologies & PHP Platform. Hands on experience with C#, VB, ASP.NET, ASP.NET MVC, ASP.NET Core, ASP.NET Web API, Linq, ADO.NET, Entity Framework, Entity Framework Core, Sql Server, MYSQL, NoSql, Javascript, Angular, jQuery, AWS, Azure, React, Angular, Laravel, Codeingiter, Serenity, VBA, Cloud Computing, Microservices, Design Patterns, Software Architecture, Web Design and Development.

Related Post