首先,我是asp mvc的新手,所以请耐心等待。
目前我想创建项目,其中 autofac 将是 IoC 容器,我将要求自定义控制器工厂。在自定义控制器工厂中,我想通过控制器的构造函数设置实现数据存储库。
我认为应该以这种方式完成:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(asm).InstancePerHttpRequest();
builder.Register(s => new ControllerFactory()).As<IControllerFactory>();
IContainer container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
我的控制器工厂代码:
internal class ControllerFactory : DefaultControllerFactory
{
private readonly Dictionary<string, Func<RequestContext, IController>> _controllerMap;
public ControllerFactory()
{
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);
}
}
控制器映射为空。当我想解决 IController 时收到错误,因为 IController 不是 reqseter,但我在 autofac builder 中使用了 RegisterControllers。
你能解释一下如何以正确的方式做到这一点吗?