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

喜欢而已 提交于 2019-12-03 10:39:18

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 with 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 Controllers
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); //Register WebApi Controllers
builder.RegisterType<Type>().As<IType>();

var container = builder.Build();

DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //Set the MVC DependencyResolver
GlobalConfiguration.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

I think you are missing registering autofac at app start code.

Use this:

protected void Application_Start()
{
    IocConfig.Config();
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
   BundleConfig.RegisterBundles(BundleTable.Bundles);
}

For more details, refer this blog http://www.codeproject.com/Articles/808894/IoC-in-ASP-NET-MVC-using-Autofac

Open you ServiceModule File

Register the Interface and service name those are mentioned in controller.

Example are as below:-

builder.RegisterType().As();

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