如何在运行时创建新控制器?

时间:2017-04-05 06:06:09

标签: c# asp.net-mvc controller-factory

想象一下在该解决方案中没有任何控制器的MVC项目。我有同样的事情,想要在运行时使用DefaultControllerFactory创建控制器,然后在我的Global.asax中通过Autofac进行注册。 这里我有一个样本控制器工厂,它有CreateController方法:

internal class CControllerFactory : DefaultControllerFactory
{
    private readonly Dictionary<string, Func<RequestContext, IController>> _controllerMap;

    public CControllerFactory()
    {
        List<IController> lstControllers = DependencyResolver.Current.GetServices<IController>().ToList();
        _controllerMap = new Dictionary<string, Func<RequestContext, IController>>();

        foreach (Controller contr in lstControllers)
        {
            string ctrName = contr.ControllerContext.RouteData.Values["Controller"].ToString();
            _controllerMap.Add(ctrName, c => contr);
        }
    }

    public override IController CreateController(RequestContext requestContext, string controllerName)
    {

        if (_controllerMap.ContainsKey(controllerName))
        {
            return _controllerMap[controllerName](requestContext);
        }
        else
            throw new KeyNotFoundException(controllerName);
    }
}

如上所示,此行:List<IController> lstControllers = DependencyResolver.Current.GetServices<IController>().ToList();将获取使用IController服务的控制器列表。但在我的情况下,解决方案中不存在控制器。我想在运行时创建一个新控制器并将其添加到我的_controllerMap

所以我把代码更改为:

internal class CControllerFactory : DefaultControllerFactory
{
    private readonly Dictionary<string, Func<RequestContext, IController>> _controllerMap;

    public CControllerFactory()
    {
         // *Don't need this*
         // List<IController> lstControllers = DependencyResolver.Current.GetServices<IController>().ToList();
        _controllerMap = new Dictionary<string, Func<RequestContext, IController>>();
         // *Don't need this Foreach*
         // foreach (Controller contr in lstControllers)
         // {
               string ctrName = "Home";
               // But what about contr in this line?!?!:
               _controllerMap.Add(ctrName, c => contr);
         // }
    }

    public override IController CreateController(RequestContext requestContext, string controllerName)
    {

        if (_controllerMap.ContainsKey(controllerName))
        {
            return _controllerMap[controllerName](requestContext);
        }
        else
            throw new KeyNotFoundException(controllerName);
    }
}

那么指定行中的contr呢?此参数必须是Func<RequestContext,IController>的类型。如何通过C#代码在功能上创建它?

0 个答案:

没有答案