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 have an ASP.NET Web API 2.0 project. I have Autofac
, Autofac.Mvc5
and Autofac.WebApi2
dependencies installed. When I try to call an API controller I get the following error:
An error occurred when trying to create a controller of type 'MyController'. Make sure that the controller has a parameterless public constructor.
In my Global.asax
I have a call to IocConfig.Config()
which I have placed inside App_Start
:
public static class IocConfig
{
public static void Config()
{
var builder = new ContainerBuilder();
builder.RegisterType<MyLogger>().As<IMyLogger>();
builder.RegisterApiControllers(Assembly.GetCallingAssembly());
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);
WebApiApplication.Container = builder.Build();
DependencyResolver.SetResolver(
new AutofacDependencyResolver(WebApiApplication.Container));
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(WebApiApplication.Container);
}
}
And this is the constructor for MyController
:
public MyController(IMyLogger logger)
When I try to call it I get the specified error about the constructor. What am I missing?
I encountered this error as well and the root cause was that one of the Controller's dependencies wasn't registered correctly in Autofac.
The InnerException has the detail (in my case it was an Autofac.Core.DependencyResolutionException) and the ExceptionMessage included the detail of this dependency. Along the lines of:
"An error occurred during the activation of a particular registration... Cannot resolve parameter 'XXXX'
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