
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Dependency Inversion Principle and Its Implementation in C#
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(); } } } }
Advertisements