Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy to refactor when too many dependencies injected into service or controller

I have an ASP.NET MVC 1 application that uses NHibernate and Castle Windsor for IoC. The controllers have service classes injected, and these service classes handle all the logic and actions required by the app. The service classes have repositories injected. Each repository handles a single object. Objects are mapped to DB table via NH. I have tried to keep a one to one relationship between services and controllers, but some services are used in more than one controller.

The problem is that some services now have dependencies on 10-15 repositories. The system has an invoicing component for example, where certain actions depend on users, customers, work orders, work order line items, invoices, invoice line items, taxes, etc.

What strategies do people used to refactor effectively when it comes to dependency overload? I'm thinking of splitting one service into many services and to remove the 1-to-1 attempt between services and controllers. But then dependencies at the controller level will increase. Splitting one controller into many controllers is possible with the prior suggestion, but I don't believe that's done unless you break views into partial views? I realize this is a broad question, but I'm more looking for guidance than exact answers. Feel free to provide links to articles or examples of similar refactoring.

like image 591
Chris F Avatar asked May 17 '11 02:05

Chris F


2 Answers

You should refactor to Facade Services, which involves sliding in a new layer of more coarse-grained services that orchestrate the finer-grained services. Currently your Controllers are doing too much fine-grained work.

FWIW chapter 6 of my book contains an example of this process and it also touches on some of the mental exercises you can do to identify the appropriate clusters of services to be grouped.

Keep in mind that a particular service can be a member of more than one cluster. That basically just indicates that this is a central service in the application.

like image 184
Mark Seemann Avatar answered Nov 17 '22 01:11

Mark Seemann


Your repository approach is flawed. Instead of having a repository for each and every entity type in your application, you should focus on your root entities. Pick a few entities that are the top level entities in your application and build your repositories around them. E.G. work order line items likely don't need their own repository, as they can't exist on their own without a work order.

Another thing you've likely created in your design is a very anemic domain layer. So your entities are pretty much just POCO objects, while all of the business logic is contained in your service layer. Consider moving some or most of that logic into the domain.

like image 35
Vadim Avatar answered Nov 17 '22 00:11

Vadim