0
我正在做一些MVC 6 alpha 4的實驗。試圖手動激活一個控制器並返回它而不是HomeController,但這不起作用。任何幫助請..在MVC 6 alpha4手動實例化一個控制器
到目前爲止,我已經創建了我自己的控制器工廠與此代碼。
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;
}
}
我已經調試了代碼。 MyController
的構造函數被調用,MyController
正在從CreateController
方法返回,但我得到錯誤。調試器永遠不會達到IActionResult Index()
。這是我得到的錯誤。
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()
「代替HomeController」是什麼意思?爲什麼不改變你的路線,以便你的「HomeController」不在這裏選擇? – bzlm 2014-12-02 19:49:56