自定义的ControllerFactory与autofac(Custom ControllerFac

2019-08-03 04:15发布

首先,我在ASP MVC一个新手,所以请耐心等待。

目前,我想创建项目中autofac将是IoC容器,我会reqister定制控制器工厂。 在自定义控制器工厂我想通过控制器的构造函数来设置实现数据存储库。

我认为应该以这种方式来完成:

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不是reqiseter但我用RegisterControllers在autofac建设者。

你能解释我如何去做正确的方式?

Answer 1:

既然你是通过接口解决控制器,使用AsImplementedInterfaces方法来注册控制器。

builder.RegisterControllers(asm).AsImplementedInterfaces()
    .InstancePerHttpRequest();


文章来源: Custom ControllerFactory with autofac