0

I am using Ninject MVC to bind the services used in my controller.

The controller is pretty complex, and has many methods, and these methods require different services.

My question is: isn't this overkill to send to the controller constructor all the services that are used in different Actions?

Would it make more sense to send in the constructor the Ninject Activator, and then use the activator to instantiate the services?

public class DefaultController : Controller
{
    private readonly Service1 _service1;
    private readonly Service2 _service2;
    private readonly Service3 _service3;

    public DefaultController(
        Service1 service1,
        Service2 service2,
        Service3 service3)
    {
        _service1 = service1;
        _service2 = service2;
        _service3 = service3;
    }

    public ActionResult Action1()
    {
        var result = _service1.GetResult();
        return View();
    }

    public ActionResult Action2()
    {
        var result = _service2.GetResult();
        return View();
    }

    public ActionResult Action3()
    {
        var result = _service3.GetResult();
        return View();
    }
}

vs

public class DefaultController : Controller
{
    private readonly IKernel _kernel;
    public DefaultController(IKernel kernel)
    {
        _kernel = kernel;
    }

    public ActionResult Action1()
    {
        Service1 _service1 = _kernel.Get<Service1>();
        var result = _service1.GetResult();
        return View();
    }

    public ActionResult Action2()
    {
        Service2 _service2 = _kernel.Get<Service2>();
        var result = _service2.GetResult();
        return View();
    }

    public ActionResult Action3()
    {
        Service3 _service3 = _kernel.Get<Service3>();
        var result = _service3.GetResult();
        return View();
    }
}
Catalin
  • 11,503
  • 19
  • 74
  • 147
  • 1
    @MarkSeemann your linked dupe is pretty fine and works nice as long as you can move the services into one facade, but what's happening when these services are doing completely different operations? Wouldn't it be a wiser idea to tell OP that he _could_ create fine-grained controllers for each services to better obey SRP? TL;DR create one controller-one action per service, it sounds more focused to me. – kayess Feb 02 '16 at 10:10
  • 1
    @kayess Indeed, aiming for SRP (and the rest of SOLID) is the goal. – Mark Seemann Feb 02 '16 at 10:12

0 Answers0