navig8tr
navig8tr

Reputation: 1854

How do I pass a value to a Controller's constructor?

So, in effort to unit test our controllers I am trying to slim down our controllers and make them more testable. We use a Service/Reposistory pattern and one issue we have is multiple instantiations of our service layer. Each method in the controller instantiates a new instance of the service layer. To correct this I would like to instantiate a single time in the Controller's constructor.

Here is an example of our typical Controller method:

public class GroupController : ControllerBase // ControllerBase is derived from System.Web.Mvc.Controller
{
    public ActionResult EditGroup(int groupId)
    {
        EditGroupViewModel model = new EditGroupViewModel();
        using (var service = new AccountServices(this.User)) // this.User is an instance of IPrincipal Controller.User            {
            Group group = service.GetGroupWithRoles(groupId);
            // some code to map Group to EditGroupViewModel
        }
        return View(model);
    }
}

Any method that uses AccountServices must instantiate a new instance of the class as shown above. Ideally, the AccountServices would be instantiated a single time in the Controller's constructor. However, I'm unsure how to do this.

Here is what I tried:

    private readonly AccountServices _service;

    public GroupController(IPrincipal user)
    {
        _service = new AccountServices(user);
    }

However, when placing a breakpoint on the constructor I see that IPrinicipal user remains null.I think my biggest obstacle is the fact that AccountServices requires an IPrincipal Controller.User to be instantiated. How can I instantiate AccounServices a single time in the constructor so that all of the Controller's methods can use the instance?

Upvotes: 2

Views: 2672

Answers (1)

Otávio Décio
Otávio Décio

Reputation: 74290

You can use dependency injection and a custom factory for that. Here's a site to get you started.

Upvotes: 4

Related Questions