Middle
What is dependency inversion in C# development?
sobes.tech AI
Answer from AI
The design principle according to which 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 C#, this is usually implemented through:
- Using interfaces or abstract classes to define contracts.
- Dependency Injection to provide specific implementations via constructors, properties, or methods.
// Abstraction
public interface IMessageSender
{
void Send(string message);
}
// Low-level module (detail)
public class EmailSender : IMessageSender
{
public void Send(string message)
{
// Email sending logic
}
}
// High-level module
public class NotificationManager
{
private readonly IMessageSender _sender;
// Dependency is injected via constructor (Dependency Injection)
public NotificationManager(IMessageSender sender)
{
_sender = sender;
}
public void Notify(string message)
{
_sender.Send(message);
}
}
In this example, NotificationManager (high-level module) depends on the abstraction IMessageSender, not on the concrete implementation EmailSender (low-level module). This makes NotificationManager more flexible and testable, as different implementations of IMessageSender can be easily used.