想象一下在该解决方案中没有任何控制器的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#代码在功能上创建它?