one.beat.consumer
one.beat.consumer

Reputation: 9504

Injecting Services into a Base Controller class

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)?

Upvotes: 6

Views: 6643

Answers (3)

Eranga
Eranga

Reputation: 32437

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.

Upvotes: 14

Alex
Alex

Reputation: 35399

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)
{

}

Upvotes: 4

Alexey Raga
Alexey Raga

Reputation: 7525

The easiest way to inject services (and other dependencies) is to use IoC/DI container. ASP.NET MVC has everything in it to make it possible, here is an explanation of how to make it happen.

Anyway, even without any DI you can build your own small IControllerActivator and inject your services there in a way it suits you.

Upvotes: -1

Related Questions