MVC Interview Question

Question 1:
Is it possible to use parameterised constructor in MVC controller? If Yes then how ?

Ans: Yes we can use parameterized constructor in MVC.
It is the responsibility of "ControllerFactory" class to initialized controller instance. In order  to use parameterised constructor we must derive  "ControllerFactory" as below

public class CustomControllerFactory : DefaultControllerFactory
{
   protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
   {
    ILogger logger = new DefaultLogger();
    IController controller = Activator.CreateInstance(controllerType, new[] { logger }) as Controller;
    return controller;
  }

}

In above code DefaultControllerFactory is derived and GetControllerInstance  is overridden to instantiate controller with "logger" parameter.

Another way and best way is to use dependency injection.

Comments

Popular Posts