Tutorial :asp.net mvc with ioc --> avoiding constructor soup with BaseController



Question:

I have a BaseController that I'm using to house my cross cutting concerns for an MVC project.

However, this means that my Controller has 3 dependencies:

 public BaseController (IUserService u, ITenantDetailsService t, ISiteConfiguration c)   

The side effect of this is that my constructors for each derived controller are awash with parameters:

  public AccountController(ILocationService locationService, IAccountService accountService, IFormsAuthentication formsAuth, IMembershipService service, IUserService userService, ISiteConfiguration configuration)        : base(locationService,userService, configuration )  

I'm using IoC (Windsor) to resolve my controllers, so know that I could remove the constructor dependencies and let it auto-wire the public properties up.

Is there a reason for not doing this other than masking some of the dependencies?

public AccountController (IAccountService, IFormsAuthentication, IMembershipService)   

This approach seems more readable and gives a clear overview of the dependencies relevant to that specific controller.

Or have I got it all wrong and a BaseController isn't the correct place to store the cross cutting services.

Thoughts appreciated.

Thanks, Chris


Solution:1

One reason I can think of is convention - many people interpret setter injection as non-required dependency and constructor injection as required. Altough - this is just a convention, and wouldn't stop me from using auto-wired properties in this example.

Dependency injection is supposed to simplify your work (I acknowledge that it's not the most important reason to use DI, but I think it is a valid reason), not make it any harder. Consider a situation when you have to add another "global" service. You would have to go through every controller in your project and modify a constructor, which is really, really bad.

I came up with another idea to solve this problem: create a collector object, that stores all "global" dependencies, get it passed to concrete controllers, then passed to the base, which would get required dependencies. It would solve problem with adding dependencies and you would clearly state, that concrete controller is passing dependencies to base class. I didn't like it though, because it still requires 2 classes to change ("dependency collector" and BaseController) when I'm adding new, "global" dependency.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »