问题
I am doing some experimentation with MVC 6 alpha 4. Trying to activate a controller manually and returning it instead of HomeController but this doesn't work. Any help please..
So far I have created my own controller factory 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 have debugged the code. The constructor of MyController
gets called and MyController
is being returned from the CreateController
method but I get the error. The debugger never reaches to IActionResult Index()
. Here is the error that I get.
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()
回答1:
Here is the answer.
Firstly, MyController
needs to inherit from HomeController
.
Secondly, I need to change the 'controller' value in RouteData before activating the controller.
actionContext.RouteData.Values["controller"] = "My";
来源:https://stackoverflow.com/questions/26325854/manually-instantiate-a-controller-in-mvc-6-alpha4