Articles → .NET DESIGN PATTERN → Dependency Inversion Principle In C#

Dependency Inversion Principle In C#






What Does The Dependency Inversion Principle State?




  1. High-level and low-level modules should depend on shared abstractions rather than depending directly on one another.
  2. Abstractions should not depend on implementation details; implementation details should depend on abstractions.



Example




public class PresentationLayer {
  public string GetMessage() {
    ApplicationLayer applicationLayer = new ApplicationLayer();
    return applicationLayer.GetWelcomeMessage();
  }
}
public class ApplicationLayer {
  public string GetWelcomeMessage() {
    return "Welcome Karan";
  }
}





Picture showing the traditional development method where high level module is dependent on low level module
Click to Enlarge



  1. Define an interface.
  2. Implement the interface in the low-level module.
  3. Use an interface as an abstraction layer between the high-level and low-level modules.


public class PresentationLayer {
  IMessage _message;
  public PresentationLayer(IMessage message) {
    this._message = message;
  }

  public string GetMessage() {
    return _message.GetWelcomeMessage();
  }
}

public interface IMessage {
  string GetWelcomeMessage();
}

public class ApplicationLayer: IMessage {
  public string GetWelcomeMessage() {
    return "Welcome Karan";
  }
}



Picture showing the Dependency Inversion principle method of implementation
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Monday, December 28, 2020

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250