The Dependency Inversion Principle states that:
- High-level modules should not depend on low-level modules. Both should depend on abstractions (e.g., interfaces).
- Abstractions should not depend on details. Details (concrete implementations) should depend on abstractions.
Source: Wikipedia
Other SOLID Principles
- Single Responsibility Principle
- Open Closed Principle
- Liskov Substitution Problem
- Interface Segregation Principle
Example without DIP
public class UserRepository
{
public string GetUserById(int id)
{
// Code to fetch user from the database
return "User";
}
}
public class UserService
{
private readonly UserRepository _userRepository;
public UserService()
{
_userRepository = new UserRepository();
}
public string GetUser(int id)
{
return _userRepository.GetUserById(id);
}
}
One problem with this code is , theUserService
is tightly coupled with the UserRepository
. Another problem is, if you want to use different implementation of UserReposoitory
, you can not easily do it. For instance you want to swap your UserRepsoitory
to UserRepositoryWithDifferentDatabase
.