自定义ControllerFactory与autofac

时间:2012-11-25 21:01:26

标签: asp.net-mvc-3 dependency-injection autofac controller-factory

首先,我是asp mvc的新手,请耐心等待。

目前我想创建一个项目,其中autofac将是IoC容器我将需要自定义控制器工厂。在自定义控制器工厂中,我想通过控制器的构造函数设置实现Data Repository。

我认为应该这样做:

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,但我在autofac builder中使用了RegisterControllers。

你能解释一下如何以正确的方式做到这一点吗?

1 个答案:

答案 0 :(得分:1)

由于您是通过接口解析控制器,因此请使用AsImplementedInterfaces方法注册控制器。

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