问题描述
我知道之前已经有人问过它了-我问的原因是(我想)我尝试了所有建议的解决方案,但仍然无法解决.
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.
我有一个ASP.NET Web API 2.0项目.我安装了Autofac
,Autofac.Mvc5
和Autofac.WebApi2
依赖项.当我尝试调用API控制器时,出现以下错误:
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:
在我的Global.asax
中,我有一个呼叫IocConfig.Config()
的呼叫,该呼叫已放置在App_Start
中:
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);
}
}
这是MyController
的构造函数:
public MyController(IMyLogger logger)
当我尝试调用它时,出现关于构造函数的指定错误.我想念什么?
When I try to call it I get the specified error about the constructor. What am I missing?
推荐答案
我也遇到了此错误,根本原因是Controller的依赖项之一未在Autofac中正确注册.
I encountered this error as well and the root cause was that one of the Controller's dependencies wasn't registered correctly in Autofac.
InnerException包含详细信息(在我的情况下为Autofac.Core.DependencyResolutionException),并且ExceptionMessage包含此依赖项的详细信息.遵循以下原则:
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:
这篇关于Autofac-确保控制器具有无参数的公共构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!