Junior — Middle
Can you explain the principle of dependency inversion and how to apply it in software development?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states that:
- 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 helps reduce coupling between components and increases flexibility and testability of the code.
In C#, this is often implemented through interfaces and dependency injection. Instead of a class directly creating or using specific implementations, it works with abstractions (interfaces), and specific implementations are passed from outside.
Example:
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine(message);
}
public class UserService
{
private readonly ILogger _logger;
public UserService(ILogger logger)
{
_logger = logger; // dependency is injected from outside
}
public void CreateUser(string name)
{
// user creation logic
_logger.Log($"User {name} created.");
}
}
// Usage:
var logger = new ConsoleLogger();
var service = new UserService(logger);
service.CreateUser("Alice");
This approach makes it easier to replace the logger implementation, simplifies testing (mock can be used), and reduces coupling.