I am working on a project with a service, repository pattern. AService, ARepository, BService, BRepository. Now, however, it happens that A has a relation to B. So I have to shoot another query against the B database to merge both objects later. For example: give me all objects A and their relation to object B. Can I call the BRepository directly from the AService or should I better go via the BService? Is there a rule here according to cleanCode?
CodePudding user response:
Sure, you can. Imagine situation, when user buy something in online shop. You would need many repositories:
public class OrderService
{
private IUserRepository _userRepository;
private IWareHouseRepository _wareHouseRepository;
OrderService(IUserRepository userRepository,
IWareHouseRepository wareHouseRepository)
{
_userRepository = userRepository;
_wareHouseRepository = wareHouseRepository;
}
}
I would prefer to call repository instead of service because repository is less specific. I mean calling another service ServiceB
that contain desired repository can be dangerous as business logic can be added into existing service ServiceB
which is not eligible for your ServiceA
.
In addition, circular dependencies can be occured if we call service from another service. So try to use dependency injection. Moreover, try to program to interfaces, not implementations, I mean you can create interfaces for your service classes and use this interface from your client classes (pass the concrete implementation to the constructor).