SOLID – Dependency Inversion Principle in C#
Dependency Inversion Principle (DIP) means high-level code should not depend directly on low-level code.
Both should depend on an abstraction, such as an interface. This makes your application easier to test, extend and maintain.
1. Why Do We Need Dependency Inversion?
Imagine a hospital manages appointments across 500 branches. Every appointment needs a reminder. Some hospitals send SMS messages. Others use email or WhatsApp.
Now imagine the appointment service directly creates an SMS sender. What happens when the hospital changes its notification provider?
Think about this before reading the code.
The problem: without Dependency Inversion
Let's start with a small hospital appointment system. It sends reminders through SMS.
The appointment service creates the SMS sender directly. This makes the service depend on one specific provider.
using System;
public class SmsAppointmentNotifier
{
public void Send(string patientName)
{
Console.WriteLine(
"SMS reminder sent to " + patientName);
}
}
public class AppointmentService
{
private readonly SmsAppointmentNotifier _notifier;
public AppointmentService()
{
_notifier = new SmsAppointmentNotifier();
}
public void BookAppointment(string patientName)
{
Console.WriteLine(
"Appointment booked for " + patientName);
_notifier.Send(patientName);
}
}
public class Program
{
public static void Main()
{
var appointmentService =
new AppointmentService();
appointmentService.BookAppointment("Priya");
appointmentService.BookAppointment("Ravi");
appointmentService.BookAppointment("Lakshmi");
}
}
Appointment booked for Priya SMS reminder sent to Priya Appointment booked for Ravi SMS reminder sent to Ravi Appointment booked for Lakshmi SMS reminder sent to Lakshmi
This code works. The problem appears when notification requirements change.
What goes wrong?
- Tight coupling: AppointmentService knows the SMS implementation.
- Risky changes: Changing providers may require changing appointment code.
- Harder testing: Tests cannot easily replace the real SMS sender.
- Limited flexibility: Supporting email needs more changes.
- Growing complexity: More providers can make the service harder to maintain.
Now think about 500 hospital branches. Each branch may use a different provider. Direct dependencies make those changes harder to manage.
What does the dependency look like?
The service directly knows the SMS class. This creates a dependency on one provider.
2. The Solution: Apply Dependency Inversion
We need the appointment service to work with different notification providers.
We can introduce an interface named IAppointmentNotifier.
Interface = a contract that describes what a class must provide.
The appointment service will depend on this interface. SMS and email classes will implement the same contract.
Implementation = the actual code that performs the required work.
How the improved design works
The business service and provider classes meet through one shared interface.
Key terms to remember
- High-level module = code that handles important business rules.
- Low-level module = code that performs a specific technical task.
- Abstraction = a simple contract that hides implementation details.
- Dependency = something another part of the code needs.
- Dependency Injection = giving an object the dependency it needs.
- Constructor Injection = passing that dependency through the constructor.
Example 2: Appointment service using DIP
We will keep the same hospital appointment example. The interface defines the notification contract.
public interface IAppointmentNotifier
{
void Send(string patientName);
}
Both notification providers must implement the Send method.
using System;
public class SmsAppointmentNotifier : IAppointmentNotifier
{
public void Send(string patientName)
{
Console.WriteLine(
"SMS reminder sent to " + patientName);
}
}
using System;
public class EmailAppointmentNotifier : IAppointmentNotifier
{
public void Send(string patientName)
{
Console.WriteLine(
"Email reminder sent to " + patientName);
}
}
using System;
public class AppointmentService
{
private readonly IAppointmentNotifier _notifier;
public AppointmentService(
IAppointmentNotifier notifier)
{
_notifier = notifier;
}
public void BookAppointment(string patientName)
{
Console.WriteLine(
"Appointment booked for " + patientName);
_notifier.Send(patientName);
}
}
The constructor receives the notification provider. The service does not create it.
using System;
public class Program
{
public static void Main()
{
IAppointmentNotifier notifier =
new SmsAppointmentNotifier();
var appointmentService =
new AppointmentService(notifier);
appointmentService.BookAppointment("Priya");
appointmentService.BookAppointment("Ravi");
appointmentService.BookAppointment("Lakshmi");
}
}
Appointment booked for Priya SMS reminder sent to Priya Appointment booked for Ravi SMS reminder sent to Ravi Appointment booked for Lakshmi SMS reminder sent to Lakshmi
Now change one line in Program. The appointment service stays unchanged.
IAppointmentNotifier notifier =
new EmailAppointmentNotifier();
var appointmentService =
new AppointmentService(notifier);
Appointment booked for Priya Email reminder sent to Priya Appointment booked for Ravi Email reminder sent to Ravi Appointment booked for Lakshmi Email reminder sent to Lakshmi
Notice the change: AppointmentService does not know whether SMS or email is used. It only knows IAppointmentNotifier.
3. Understand the Code Step by Step
Why do we create an interface?
IAppointmentNotifier defines one shared notification contract. It does not contain provider-specific sending code.
Why do both providers implement it?
SmsAppointmentNotifier and EmailAppointmentNotifier provide their own Send method. Both follow the same contract.
Why does AppointmentService accept an interface?
The service only needs a notification capability. It does not need to know the provider's internal details.
Why use constructor injection?
The constructor receives the required dependency from outside. This makes the service easier to test and replace.
Why is Program responsible for creating the provider?
Program is the composition point in this small example. It connects the service with the chosen implementation.
4. Dependency Inversion vs Dependency Injection
These terms are related, but they do not mean the same thing.
| Dependency Inversion | Dependency Injection |
|---|---|
| A design principle. | A technique used to provide dependencies. |
| Defines how modules should depend on abstractions. | Passes required objects into another object. |
| Reduces direct dependencies between modules. | Can provide replaceable implementations. |
| Can be applied without a DI container. | Can be done manually or with a DI container. |
Our example follows DIP through an interface. It uses constructor injection to provide the implementation.
5. The SOLID Dependency Rule
The Dependency Inversion Principle has two important rules.
- 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.
In our example, AppointmentService is the high-level module. It contains the appointment booking rule.
SmsAppointmentNotifier is a low-level module. It handles one specific notification method.
IAppointmentNotifier is the abstraction. Both sides depend on this contract.
6. Real-World Architecture and Trade-Offs
How this helps in larger applications
- Testing: You can pass a fake notifier during unit tests.
- Maintainability: Provider changes do not need to change booking rules.
- Extensibility: New providers can implement the same interface.
- Separation: Business rules stay separate from external services.
- Flexibility: Different environments can use different implementations.
Where should the interface live?
Keep the abstraction close to the business rules it serves. Avoid making business logic depend on infrastructure projects.
For a larger solution, you could organize projects like this:
The application uses a domain contract. Infrastructure projects implement that contract.
Important production considerations
- Keep provider credentials in secure configuration.
- Handle provider failures and network timeouts.
- Use retries carefully to avoid sending duplicate reminders.
- Log delivery outcomes without exposing patient information.
- Use queues when notification work must run asynchronously.
- Keep provider-specific settings outside the appointment business rules.
Important: An interface alone does not make an application reliable. You still need error handling, secure configuration and monitoring.
7. Common Mistakes and Best Practices
Mistake 1: Creating the implementation inside the service
Wrong: AppointmentService creates SmsAppointmentNotifier using new.
Why it fails: The service becomes tied to one provider.
Better: Accept IAppointmentNotifier through the constructor.
Mistake 2: Creating an interface for every class
Why it fails: Extra interfaces can make simple code harder to follow.
Better: Create an abstraction when it provides a useful boundary or replaceable behavior.
Mistake 3: Putting provider details inside the interface
Wrong: Add SMS account settings and email server settings to one contract.
Why it fails: The interface becomes tied to specific providers.
Better: Keep the contract focused on the business capability.
Mistake 4: Confusing DIP with a DI container
Why it fails: A container does not automatically create a good design.
Better: First define clean abstractions. Then choose how to provide implementations.
Mistake 5: Making the interface too large
Why it fails: Every provider must implement methods it may not need.
Better: Keep interfaces small and focused on one clear responsibility.
Best practices checklist
- Make business logic depend on interfaces where useful.
- Keep infrastructure details outside core business rules.
- Use constructor injection for required dependencies.
- Keep interfaces small and meaningful.
- Test business logic with fake implementations.
- Register real implementations at the application startup point.
- Avoid adding abstractions without a clear reason.
8. How Dependency Inversion Appears in Interviews
Question 1: What is the Dependency Inversion Principle?
What the interviewer expects: A clear definition and a practical example.
Strong answer:
"Dependency Inversion means high-level code should not depend directly on low-level code. Both should depend on abstractions. In a hospital appointment system, the booking service should depend on an appointment notifier interface. SMS and email providers can implement that interface. This keeps booking logic independent of the notification provider."
Question 2: What is the difference between DIP and Dependency Injection?
Strong answer:
"DIP is a design principle. Dependency Injection is a way to provide dependencies. I can follow DIP with manual constructor injection. I can also use a DI container to register and resolve implementations."
Question 3: How does DIP improve unit testing?
Strong answer:
"The appointment service depends on an interface. During a unit test, I can pass a fake notifier. I can test the booking logic without calling a real SMS or email provider."
Question 4: Does every class need an interface?
Strong answer:
"No. I create interfaces when they provide a useful boundary. They are helpful when implementations may change, need testing or belong to separate layers. I avoid adding interfaces without a clear reason."
What changes at different experience levels?
| Level | What to explain |
|---|---|
| Junior | Explain interfaces and constructor injection. |
| Senior | Explain testing, replaceable providers and maintainability. |
| Architect | Explain dependency direction across application boundaries and infrastructure. |
9. Hands-On Practice
Beginner: Add a WhatsApp notification provider
Use the hospital appointment example. Create a WhatsApp notifier that implements IAppointmentNotifier.
Expected result: AppointmentService should work without changing its code.
Intermediate: Write a fake notifier for testing
Create a FakeAppointmentNotifier class. Make it store the patient name instead of sending a message.
Hint: Implement IAppointmentNotifier and save the received name in a property.
Advanced: Support multiple notification providers
Allow the application to select SMS or email through configuration. Keep provider selection outside AppointmentService.
Hint: Register the selected implementation at the application's composition point.
Practice questions
- What happens if AppointmentService creates its own SMS provider?
- Why should the interface not contain provider-specific settings?
- Can you follow DIP without using a DI container?
- How would you test appointment booking without sending real messages?
- Where should infrastructure implementations be registered?
10. Frequently Asked Questions
Is Dependency Inversion the same as Dependency Injection?
No. DIP is a design principle. Dependency Injection is a technique for providing dependencies.
Can we use Dependency Inversion without interfaces?
Yes. Other abstractions can also help. In C#, interfaces are a common way to express contracts.
Does DIP improve performance?
DIP mainly improves design and maintainability. It does not automatically make code faster.
Does DIP require a dependency injection framework?
No. You can provide dependencies manually through constructors or other suitable methods.
Where should interfaces be placed in a layered application?
Place them near the policy or layer that owns the contract. Keep infrastructure implementations separate.
11. Next Steps and Community
You have now learned how Dependency Inversion reduces direct dependencies. You also saw how interfaces help separate business rules from technical details.
Try adding another notification provider. Then test the appointment service with a fake implementation.
Share your implementation and discuss other design choices with the Upgradix community.
Learn Technology. Build Your Future.
Upgradix by Shrash Studio — Quality Technology Education. Completely Free.