Manually instantiate controller in MVC 6 alpha4
I am experimenting with MVC 6 alpha 4. Trying to activate the controller manually and return it instead of the HomeController, but it doesn't work. Any help please.
So far I have created my own factory controller with this code.
public class MyControllerFactory : IControllerFactory
{
public object CreateController(ActionContext actionContext)
{
var actionDescriptor = actionContext.ActionDescriptor as Microsoft.AspNet.Mvc.ReflectedActionDescriptor;
Type controllerType = Type.GetType("Hello.Controllers.MyController");
var controller = _typeActivator.CreateInstance(_serviceProvider, controllerType);
actionContext.Controller = controller;
_controllerActivator.Activate(controller, actionContext);
return controller;
}
}
I was debugging the code. The constructor MyController
is called and MyController
returned from the method CreateController
, but I am getting the error. The debugger never reaches IActionResult Index()
. Here is the error I am getting.
System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Microsoft.AspNet.Mvc.ReflectedActionExecutor.<ExecuteAsync>d__2.MoveNext()
0
source to share