What is dependency inversion principle and how to implement in C#?

CsharpServer Side ProgrammingProgramming

High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions.This principle is primarily concerned with reducing dependencies among the code modules.

Example

Code Before Dependency Inversion

using System;
namespace SolidPrinciples.Dependency.Invertion.Before{
   public class Email{
      public string ToAddress { get; set; }
      public string Subject { get; set; }
      public string Content { get; set; }
      public void SendEmail(){
         //Send email
      }
   }
   public class SMS{
      public string PhoneNumber { get; set; }
      public string Message { get; set; }
      public void SendSMS(){
         //Send sms
      }
   }
   public class Notification{
      private Email _email;
      private SMS _sms;
      public Notification(){
         _email = new Email();
         _sms = new SMS();
      }
      public void Send(){
         _email.SendEmail();
         _sms.SendSMS();
      }
   }
}

Code After Dependency Inversion

using System.Collections.Generic;
namespace SolidPrinciples.Dependency.Invertion.Before{
   public interface IMessage{
      void SendMessage();
   }
   public class Email: IMessage{
      public string ToAddress { get; set; }
      public string Subject { get; set; }
      public string Content { get; set; }
      public void SendMessage(){
         //Send email
      }
   }
   public class SMS: IMessage{
      public string PhoneNumber { get; set; }
      public string Message { get; set; }
      public void SendMessage(){
         //Send Sms
      }
   }
   public class Notification{
      private ICollection<IMessage> _messages;
      public Notification(ICollection<IMessage> messages){
         this._messages = messages;
      }
      public void Send(){
         foreach (var message in _messages){
            message.SendMessage();
         }
      }
   }
}
raja
Published on 05-Dec-2020 06:28:55
Advertisements