Articles → .NET DESIGN PATTERN → Dependency Inversion Principle In C#
Dependency Inversion Principle In C#
What Does The Dependency Inversion Principle State?
- High-level and low-level modules should depend on common abstractions instead of directly depending on one another.
- Abstractions should remain independent of implementation details, while implementation details should rely on 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
- Define an interface.
- Implement the interface in the low-level module.
- Use the interface to interact with the low-level module from the high-level module.
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
| Posted By - | Karan Gupta |
| |
| Posted On - | Monday, December 28, 2020 |