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.
To setup Autofac for Web.API you need to do two things:
Register the Autofac dependency resolver (in the App_Start):
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container);
And register your Api controllers in your container builder with the call:
containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With