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?
Asked
Active
Viewed 837 times
1
-
1I'd suggest viewing [Sandro Mancuso : Crafted Design](https://vimeo.com/107963074), especially from minute 10:40. There are what he calls _"actions"_ (also known as _use-cases_, or _application services_) and _"domain services"_ and their relationships. PS: You shouldn't restrict the use of a certain service to the use of a certain [repository](https://www.martinfowler.com/eaaCatalog/repository.html). – PajuranCodes Oct 09 '22 at 14:01
-
@dakis Thanks for your comment and the link. i will have a look. What do you mean by "PS: You should not restrict the use of a particular service to the use of a particular repository." You mean that a repository should be accessible for several services? – Max Pattern Oct 09 '22 at 17:38
-
Yes, this is, indeed, what I meant. Though, you should try to follow the principles from the video presentation. – PajuranCodes Oct 10 '22 at 00:48
1 Answers
1
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).

StepUp
- 36,391
- 15
- 88
- 148
-
Thank you for your good answer! I will have to think about it some more but it sounds logical. Why do you think dependency injection should be used? – Max Pattern Oct 10 '22 at 08:12
-
1@MaxPattern as it is better sometimes program to interface and writing unit tests will become easier – StepUp Oct 10 '22 at 08:21