In multi-tier architecture with a service layer, is it acceptable to have one service call another service?

StackOverflow https://stackoverflow.com/questions/7907413

Question

I have a multi-tiered app with a data layer containing repositories.

On top of this, I have a service layer. My understanding is that there should be a single service for each repository.

Is it ok to have Service A make a call to another method in ServiceB? This would, of course, create a dependency on Service B in Service A(I am using interfaces and DI).

In my example I have a User service which handles, adding users, authenticating users, finding a user by ID, etc. I also have a Book service which allows me to add book for a specific user.

Should the book service make a call to the user service to retrieve a User instance for which to add books to?

Was it helpful?

Solution

Short answer: yes

A bit less short:

Your alternatives are to either let the "book service" directly access the "user repository" or to extend the user service so it is able to add a book - neither a good option... so it is correct to do what you describe (Book Service accesses user service)... a more "pure option" would be to create a controller/aggregate/transaction/coordinator service that uses the book service and the user service to achieve what you describe, this way both "direct services" (book and user) stay "dependency-free"...

OTHER TIPS

Yes this is acceptable, as long as it makes sense to do so.

If the book service requires logic to run from the user service, and the book service does not call on the user service, you will have to duplicate the user service logic in the book service. This means that if your business logic changes for what the service logic does, you have to make sure to update the book service with the logic, or else you will have bugs and inconsistent (and unexpected) behavior.

However, if you find this happening a lot, you might have to start looking at what functionality each service does, and possibly break them apart into smaller services.

User mentioned he was using EF. In this case he can either pass the User Object to the Book Service or the User Id and create a User Object in the Book Repository before the save.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top