Articles → .NET DESIGN PATTERN → Dependency Inversion Principle In C#
Dependency Inversion Principle In C#
What Does The Dependency Inversion Principle Say?
- High-level modules should not depend upon the low-level module. Both modules should depend upon the abstractions.
- Abstractions should not depend upon details. Details should depend upon the abstractions.
Example
public class PresentationLayer {
public string GetMessage() {
ApplicationLayer applicationLayer = new ApplicationLayer();
return applicationLayer.GetWelcomeMessage();
}
}
public class ApplicationLayer {
public string GetWelcomeMessage() {
return "Welcome Karan";
}
}
Click to Enlarge
- Create an interface.
- Implement the low-level module with the interface.
- Call the low-level module in the high-level module using an interface
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";
}
}
Click to Enlarge