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

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


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'


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 Controllersbuilder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllersbuilder.RegisterType<Type>().As<IType>();var container = builder.Build();DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolverGlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver((IContainer)container); //Set the WebApi DependencyResolver


Assembly.GetCallingAssembly() will return the calling assembly, not the assembly where your types is defined.

Assembly.GetCallingAssembly Method
Returns the Assembly of the method that invoked the currently executing method.

In order to make it works, you should use typeof(IocConfig).Assembly or Assembly.GetExecutingAssembly