MVC Web API not working with Autofac Integration

前端 未结 2 699
南旧
南旧 2020-12-03 13:43

I used the MVC integration from autofac like this:

...
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(containe         


        
相关标签:
2条回答
  • 2020-12-03 14:19

    Following is a very good example

    Using Autofac with Web Api

    0 讨论(0)
  • 2020-12-03 14:29

    ASP.Net Wep.API and ASP.NET MVC uses two different IDependencyResolver (because they designed the Wep.API to not depend on ASP.NET MVC) so you need to setup both:

    var container = builder.Build();
    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    GlobalConfiguration.Configuration.DependencyResolver = 
         new AutofacWebApiDependencyResolver(container);
    

    So the AutofacDependencyResolver is needed to inject decencies to regular MVC Controller derived controllers.

    And the AutofacWebApiDependencyResolver is needed to inject dependencies to the Web.API ApiController derived controllers.

    And don't forget to register your Api controllers in your container builder with the call (it differs from usual builder.RegisterControllers method):

    builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
    
    0 讨论(0)
提交回复
热议问题