Scenario:
An MVC3 app that uses constructor injection to provide services for a given controller:
public class HomeController : BaseController
{
private readonly IArticleService _articleService;
public HomeController(IArticleService articleService)
{
_articleService = articleService;
}
public ActionResult Index()
{
// do stuff with services
return View()
}
}
Intention:
I have a UserService that fetches user principal data from Active Directory that I want usable from all my Controllers, from the base controller.
I have tried to inject this service into my BaseController like this:
public class BaseController : Controller
{
private readonly IUserService _userService;
public BaseController(IUserService userService)
{
_userService = userService;
}
}
All by itself it looks fine, but now the constructor in my HomeController is off, as it needs a : base() initializer. The trouble is, the base initializer is not parameterless due the UserService injection.
public HomeController(IArticleService articleService) : base(IUserService userService)
The code above results in syntax errors.
Question(s):
How do I properly inject a service into my BaseController and initialize it from the child Controller classes (ex. HomeController)?
The user service interface must be included in the child controllers’ constructor arguments in addition to the base initializer arguments. Like this:
Note: in order to do anything with the base controller’s
UserServicefrom the inherited controllers, change the access modified fromprivatetoprotected.