4
votes

I have an ASP.NET MVC project with a Data layer (NHibernate and Repository pattern) a Service Layer and a Web (MVC) layer.

At the moment, for each Controller in the Web layer I have a matching service class in the Service Layer. This works fine, although there is some duplication of interface and logic between the service classes (more than one class needs a GetThingById() method) and my Home Controller uses multiple services (or there would be a huge amount of duplication in a dedicated Home controller).

Is there a better way to structure this?

3

3 Answers

3
votes

Duplication usually means refactoring: Extract duplicated logic into it's on service, break everything down (Single Responsibility Principle) until there is no more duplication.

You then either simply inject multiple services into your controllers (as you already did for your home controller), or you may create classes which combine multiples services (see also Delegation, Facade, Decorator pattern and refactoring to aggregate services) and inject those.

2
votes

There is no silver bullet so you won't get the "correct" answer here. It depends on your specific scenario.

I personally try to avoid adding so many layers unless very necessary, IMO, you need a very strong motivation to have so many abstraction layers since normally you can create a suitable architecture with less components.

I'd say that for an average application you don't even need a formal service layer as it ends up being a bunch of empty methods that just call another method in your repository.

If you need to use a service layer may be more suitable to have one service class per domain entity or per group of entities. Don't think that having a service class per controller make a lot of sense. You could add some helper classes to cover common controller logic if necessary.

The problem I see with with your approach is that you service layer should be part of the model and don't think that making it so dependent on your controller layer is a good strategy.

0
votes

In "Programming Microsoft ASP.NET MVC", Dino Esposito recommends a pattern he calls 'IPODD'. I have little experience with MVC but this chapter is worth reading if you can get hold of it. I would say it offers an experienced insight into your question.

You can preview the book's explanation about the iPODD pattern here.