Autofac - Make sure that the controller has a parameterless public constructor

后端 未结 6 1213
情歌与酒
情歌与酒 2021-02-07 04:28

I know it\'s been asked and answered before - the reason I\'m asking is because (I think) I tried all suggested solutions to this problem but still can\'t resolve it.

I

6条回答
  •  [愿得一人]
    2021-02-07 05:11

    Check this answer.
    It helps me configure correct ContainerBuilder() for WebApi controllers.

    If you are looking here a solution for such error you should check your DependencyResolver Configuration first.

    I faced the same issue and the problem was that I was using Autofac code samples for ContainerBuilder() object for MVC controllers and not API.

    My code for register both type of controllers (MVC and Api):

    var builder = new ContainerBuilder();
    builder.RegisterControllers(Assembly.GetExecutingAssembly()); //Register MVC Controllers
    builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
    builder.RegisterType().As();
    
    var container = builder.Build();
    
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolver
    GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver
    

提交回复
热议问题