[英]Design pattern for a base controller with dependecy injection - MVC 3 + Ninject
我有這種模式
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;
}
}
所以我能夠做這樣的事情
public class HomeController : BaseController
{
public ActionResult Index()
{
return View(rep.Offers.GetAll());
}
public ActionResult Sections()
{
return View(env);
}
}
在我的所有控制器中。 我確信這是DI和IoC的反模式,所以我簡化了這樣的解決方案
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) { }
...
}
但是這個解決方案要求我在所有控制器中插入所有依賴項並更新所有構造函數,如果我需要一個新的全局變量(如rep)或一個新的私有變量用於basecontroller(如man)。
我應該遵循哪種模式?為什么?
在這種情況下,您似乎不需要BaseController。 我認為做這樣的事情會更容易(也更容易測試):
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;
}
}
然后,您可以讓您的IoC容器自動為每個控制器連接所有這些依賴項。
我不認為你需要總是聲明rep,man和env。 您可以利用默認/可選參數。
public BaseController(RepositoryFactory rep = null, ManageRoles man = null, ElementAvailableForUser env = null)
{
_rep = rep;
_man = man;
_env = env;
}
然后您可以使用命名參數分配:
public class HomeController : BaseController
{
public HomeController(ManageRoles man) : base(man: man) { }
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.