Custom ControllerFactory with autofac

2020-07-30 02:25发布

问题:

First of all i am a newbie in asp mvc so please be patient.

Currently I want to create project where autofac will be IoC container i will reqister custom controller factory. In custom controller factory I want to set implementation Data Repository via constructor of controller.

I thought it should be done in that way:

ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterControllers(asm).InstancePerHttpRequest();
        builder.Register(s => new ControllerFactory()).As<IControllerFactory>();
        IContainer container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

My Controller factory code:

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);
    }
}

Controller map is empty. WHen i want to resolve IController i receive and error because IController is not reqiseter but i used RegisterControllers in autofac builder.

Could you explain me how to do it in the right way?

回答1:

Since you are resolving controllers through interfaces, use the AsImplementedInterfaces method to register the controllers.

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