Controller Design – Calling Service and Repository Layers

Architecturedesign-patternsrepositoryserviceweb

A question came to the team and I'm asking you guys. Our application uses MVC with service layer. But sometimes our service layer just call the repository, without doing nothing

Our questions is: in this cases is it ok to call the repository directly from controller? For example: let's say a controller that call service when have business logic and then the service calls the repository. But when there's no logic to use in just a direct select, the controller would call the repository.

Best Answer

If your repository layer is properly abstracted (eg, the service layer and controller can only access the repository via interfaces), then:

  1. Having the controller access the repository directly simplifies that part of the code as it removes an unnecessary level of abstraction, but
  2. You are then coupling the controllers to both the service and repository layers, which can increase complexity, and
  3. You may be creating a maintenance problem should you need to add business logic at that point in the future and thus would have to "re-plumb" that part of the code, but
  4. The YAGNI ("You ain't gunna need it") principle comes in to play here, so it's unlikely you should allow such potential future issues to affect the design now.

On balance, I'd stick with feeding everything through the service layer. But that's pure opinion; accessing the repository directly is equally valid.

If your repository layer isn't properly abstracted (ie the service layer deals directly with concrete repository/database classes), then:

  1. Fix it!
  2. Do not have the controllers go anywhere near the repository until you have fixed it, as this path leads to testing hell.