nav
nav

Reputation: 509

Programming Design Architecture Q

I am architecting a WebAPI. In that WebAPI, I have the following structure using DI (IoC):

Controllers -> Services -> Repositorys  -> EF : DB.

Now when a request can use multiple services what is best practice:

Controller -> ServiceOne/ServiceTwo -> Repositories

Where ServiceTwo is instantiated in ServiceOne's constructor (or) ServiceTwo and ServiceOne or both instantiated in Controller constructor.

I am trying to achieve separation of concerns and stuck on this implementation. I am also trying to accomplish good organization of code and less code duplication.

Thoughts?

Upvotes: 0

Views: 31

Answers (1)

Zeus
Zeus

Reputation: 6566

I'm posting it as answer in addition to the comment as it exceed the lenght.

I'd say injecting serviceTwo into serviceOne would be good approach as controller does not have to deal with a lot of if elses to decide which service to go with. let the service layer followup with other services and conglomerate the data and return it to the controller.

If you have services injected within the services

Pros:

  1. Service layers tend to have transactions on each of the method, if you are dealing with a lot of calls to several different services then they all go under one big transaction.
  2. Controller just delegates the request to a service where all the business logic happens, you can ensure separation of concerns.
  3. We can reuse the services in several different combinations if possible.
  4. Error handling would become easier
  5. Controller can concentrate more on how and what type of data to return etc,

Cons:

  1. You cannot create a child transaction within a transaction if using spring transactionals

If you have services injected into the controller

Pros:

  1. You can create a new transaction for each service. Ofcoz this service cannot create a child transaction boundary.

Cons:

  1. If you have a lot of services within the controller then each service call falls in as a different transaction, so, if one fails the other service calls are not rolledback.
  2. Controller is the one which is clubbing/merging several services to get the task done.
  3. Re-usability will be reduced

Upvotes: 1

Related Questions