MVC Web API 无法与 Autofac 集成一起使用

2024-05-09

我使用了 autofac 的 MVC 集成,如下所示:

...
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

但现在我想使用新的 Web Api RTM 重新创建解决方案。 我想使用新的 AutofacWebApiDependencyResolver 类。

但是如果我使用 AutofacWebApiDependencyResolver 执行此操作,我会收到此错误:

类型 Autofac.Integration.WebApi.AutofacWebApiDependencyResolver 似乎没有实施 Microsoft.Practices.ServiceLocation.IServiceLocator。

我读到我现在必须执行此操作来设置解析器:

GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

但如果我用'='设置它,它就不会设置。它仍然是 DefaultResolver...

如果我再次使用 MVC AutofacDependencyResolver 类,它就可以工作。

autofac 和 web api rtm 仍然存在问题吗? (当前集成为RC版本)


ASP.NET Web.API 和 ASP.NET MVC 使用两种不同的IDependencyResolver(因为他们设计的 Web.API 不依赖于 ASP.NET MVC)所以您需要同时设置:

var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = 
     new AutofacWebApiDependencyResolver(container);

So the AutofacDependencyResolver需要向常规 MVC 注入礼仪Controller派生控制器。

And the AutofacWebApiDependencyResolver需要将依赖项注入到 Web.APIApiController派生控制器。

并且不要忘记通过调用在容器构建器中注册 Api 控制器(它与通常的不同)builder.RegisterControllers方法):

builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC Web API 无法与 Autofac 集成一起使用 的相关文章

随机推荐