在看MVC框架源码时,因为Action调用需要获取参数的ModelBinder,绑定参数,过程复杂。所以将Action调用抽象出来。
IActionInvoker:
public interface IActionInvoker { void InvokeAction(ControllerContext controllerContext, string actionName); }
ControllerActionInvoker:
public class ControllerActionInvoker : IActionInvoker { public IModelBinder ModelBinder { get; private set; } public ControllerActionInvoker() { this.ModelBinder = new DefaultModelBinder(); } public void InvokeAction(ControllerContext controllerContext,string actionName) { MethodInfo method = controllerContext.Controller.GetType().GetMethods().First(m => string.Compare(actionName, m.Name, true) == 0); List<object> parameters = new List<object>(); foreach (ParameterInfo parameter in method.GetParameters()) { parameters.Add(this.ModelBinder.BindModel(controllerContext, parameter.Name, parameter.ParameterType)); } ActionResult actionResult = method.Invoke(controllerContext.Controller,parameters.ToArray()) as ActionResult; actionResult.ExecuteResult(controllerContext); } }