Design pattern for base controller with dependecy injection - MVC 3 + Ninject

I have this template

public abstract class BaseController : Controller { readonly RepositoryFactory _rep; protected RepositoryFactory rep { get { return _rep; } } readonly ManageRoles _man; readonly ElementAvailableForUser _env; protected ElementAvailableForUser env { get { return _env; } } public BaseController() : this(DependencyResolver.Current.GetService<RepositoryFactory>(), DependencyResolver.Current.GetService<ManageRoles>(), DependencyResolver.Current.GetService<ElementAvailableForUser>()) { } public BaseController(RepositoryFactory rep, ManageRoles man, ElementAvailableForUser env) { _rep = rep; _man = man; _env = env; } } 

so i can do something like this

 public class HomeController : BaseController { public ActionResult Index() { return View(rep.Offers.GetAll()); } public ActionResult Sections() { return View(env); } } 

all over my controller. I am sure that it is antipattern for DI and IoC, so I thin this solution

 public abstract class BaseController : Controller { ... // removed empty constructor public BaseController(RepositoryFactory rep, ManageRoles man, ElementAvailableForUser env) { _rep = rep; _man = man; _env = env; } } public class HomeController : BaseController { public HomeController(RepositoryFactory rep, ManageRoles man, ElementAvailableForUser env) : base(rep, man, env) { } ... } 

but this solution requires me to insert all the dependencies into all the controllers and update all the constructors if I need a new global variable (e.g. rep) or a new private variable for the base controller (e.g. man).

Which template should I follow and why?

Edit I found this question and this one , but still I cannot figure out which design patterns I should follow.

+4
source share
2 answers

In this case, it looks like you need a BaseController. I think it would be easier (and more verifiable) to do something like this:

  public class HomeController : Controller { private readonly IRepository<Offers> _repository; private readonly RoleManager _roleManager; private readonly UserManager _userManager; public HomeController(IRepository<Offers> repository, RoleManager roleManager, UserManager userManager) { _repository = repository; _roleManager = roleManager; _userManager = userManager; } } 

You can then connect your IoC container to each of these dependencies automatically for each controller.

+3
source

I do not think that with a subtle solution you need to always declare rep, man and env. You can use the default / optional options.

 public BaseController(RepositoryFactory rep = null, ManageRoles man = null, ElementAvailableForUser env = null) { _rep = rep; _man = man; _env = env; } 

Then you can use named parameter assignments:

 public class HomeController : BaseController { public HomeController(ManageRoles man) : base(man: man) { } ... } 
0
source

All Articles