2

I have a very simple question. What is the best design to call another microservice, do it into service layer or repository layer?

My project has the layers Controller -> Service -> Repository. Assuming from MicroserviceA I want to call MicroserviceB, in what layer should I do the call?

I know repository is to interact with the persistence data (calls to DB mainly), but, is used also to call another service?

I've found multiple definitions and examples over internet, like this answer where it says:

the repository is responsible for mapping your data from the storage format to you business objects. It should handle both how to read and write data(delete, update too) from and to the storage.

The purpose of service layer on the other hand is to encapsulate business logic into a single place to promote code reuse and separations of concerns.

And this answer

Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database.

So I can think the call to another microservice can be done in Service layer because is part of the business logic and not involve the DB, but on the other hand, can the another microservice be considered "storage" and then the repository has to map the response to a business model?

Thanks.

J.F.
  • 13,927
  • 9
  • 27
  • 65

1 Answers1

4

This is going to be an opinionated answer and others may disagree, but I believe the repository pattern here should be concerned with abstracting the data persistence and not relate to service dependencies. At least I believe it would be a mistake to implement a service dependency in the same repository pattern that is used to access a DB.

To model a service dependency I would typically implement a dedicated component that represents the service connector and abstracts the required communication for use in the business logic and deals with the versioning issue, etc. This is comparable to creating a client library component. The interface that the component provides should be as simple as possible and could be tailored to the needs of the business component or be of a more general nature when used in multiple places. Such a client library may even be provided by the team that offers the service in the first place.

Oswin Noetzelmann
  • 9,166
  • 1
  • 33
  • 46