MVC WebApi not using AutofacWebApiDependencyResolver

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

I have a mixed MVC 4 app, where some controllers are regular implementations of Controller and some controllers are implementations of ApiController. I'm also using Autofac for DI, but it appears that the WebApi controller "activator" machinery (for lack for a more specific term) is not using the Autofac resolver (AutofacWebApiDependencyResolver), which leads to an exception being thrown when I make a request against one of my api controllers. Here's the error:

<Error>     <Message>An error has occurred.</Message>     <ExceptionMessage>         Type 'MyApp.Areas.Api.Controllers.MyController' does not have a default constructor     </ExceptionMessage>     <ExceptionType>System.ArgumentException</ExceptionType>     <StackTrace>         at System.Linq.Expressions.Expression.New(Type type)          at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)          at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)          at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)     </StackTrace> </Error> 

Here's how I set it up:

DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container); 

My understanding of the Autofac.WebApi integrations is that the above is the only requirement for getting WebApi to use the Autofac resolver, so what might be going on?

side note: The only goofy part of this that I can think of that might have bearing is that I have WebApi controllers in an MVC Area which isn't supported by the DefaultHttpControllerSelector, so implemented a custom one (vis-à-vis Andrew Malkov). I don't intuit that this would have any bearing on the resolver, though, because the selector only returns a type which is later used in activation.

回答1:

To setup Autofac for Web.API you need to do two things:

  1. Register the Autofac dependency resolver (in the App_Start):

    GlobalConfiguration.Configuration.DependencyResolver =      new AutofacWebApiDependencyResolver(container); 
  2. And register your Api controllers in your container builder with the call:

    containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 


回答2:

Probably this blog can help you: http://blogs.msdn.com/b/roncain/archive/2012/07/16/dependency-injection-with-asp-net-web-api-and-autofac.aspx



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!