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()
}
}
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.
How do I properly inject a service into my BaseController
and initialize it from the child Controller classes (ex. HomeController)?
How can we inject the service dependency into the controller C# Asp.net Core? ASP.NET Core injects objects of dependency classes through constructor or method by using built-in IoC container. The built-in container is represented by IServiceProvider implementation that supports constructor injection by default.
On MSDN: "The base class for all controllers is the ControllerBase class, which provides general MVC handling. The Controller class inherits from ControllerBase and is the default implement of a controller."
Using dependency injection, we modify the constructor of Runner to accept an interface ILogger, instead of a concrete object. We change the Logger class to implement ILogger. This allows us to pass an instance of the Logger class to the Runner's constructor.
The user service interface must be included in the child controllers' constructor arguments in addition to the base initializer arguments. Like this:
public class HomeController : BaseController
{
private readonly IArticleService _articleService;
public HomeController(IArticleService articleService, IUserService userService) : base(userService)
{
_articleService = articleService;
}
public ActionResult Index()
{
// do stuff with services
return View()
}
}
Note: in order to do anything with the base controller's UserService
from the inherited controllers, change the access modified from private
to protected
.
You need to add IUserService
as a Constructor Parameter
and pass it down to the Base implementation. If the Ninject Container
config is valid this should suffice:
public HomeController(IArticleService articleService, IUserService userService) :
base(userService)
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With