Service : Service shouldn't have multiple repositories dependencies
What is it?
This practice is activated when a service class depends on multiple repository interfaces, indicating a potential violation of the single responsibility principle and increased coupling within the service layer.
Why apply it?
Reducing a service's dependencies to a single repository or a cohesive group of repositories is crucial to maintain code clarity, facilitate easier testing, and enhance maintainability by ensuring the service remains focused on a specific domain or responsibility.
How to fix it?
Refactor the service to consolidate repository interactions, possibly by using a single or aggregated repository, or by delegating some interactions to another service or a dedicated class that encapsulates multi-repository operations.
Read more:
https://martinfowler.com/bliki/AnemicDomainModel.html
Examples
Example 1:
Negative
Incorrect implementation that violates the practice.
using Microsoft.Data.SqlClient;
namespace Practices.DDD.Service.SQLTransaction
{
public class OrderStatusService
{
private readonly OrderRepository _orderRepository;
private readonly OrderStatusRepository _orderStatusRepository;
public OrderStatusService(OrderRepository orderRepository, OrderStatusRepository orderStatusRepository)
{
_orderRepository = orderRepository;
_orderStatusRepository = orderStatusRepository;
}
public void UpdateData(Order order, int status)
{
//Process Order
_orderRepository.UpdateData(order);
//Process Status
_orderStatusRepository.UpdateStatus(order, status);
}
}
}