问题描述
我像这样使用了 autofac 的 MVC 集成:
I used the MVC integration from autofac like this:
...
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
但现在我想用新的 Web Api RTM 重新创建解决方案.我想使用新的 AutofacWebApiDependencyResolver 类.
But now I want to recreate the solution with the new Web Api RTM.And I want to use the new AutofacWebApiDependencyResolver class.
但是,如果我使用 AutofacWebApiDependencyResolver 执行此操作,则会出现此错误:
But if I do this with AutofacWebApiDependencyResolver i got this error:
类型 Autofac.Integration.WebApi.AutofacWebApiDependencyResolver似乎没有执行Microsoft.Practices.ServiceLocation.IServiceLocator.
我读到我现在必须这样做才能设置解析器:
I read that i have to do this now for setting the resolver:
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
但是如果我用'='设置它,它就没有设置.它仍然是 DefaultResolver...
But if I set it with '=', it is not set. Its still the DefaultResolver...
如果我再次使用 MVC AutofacDependencyResolver 类,它会起作用.
If I use the MVC AutofacDependencyResolver class again, it works.
autofac 和 web api rtm 仍然存在问题吗?(目前集成的是RC版)
Are were still problems with autofac and web api rtm? (the current integration is RC version)
推荐答案
ASP.Net Wep.API 和 ASP.NET MVC 使用两种不同的 IDependencyResolver
(因为他们设计的 Wep.API 不依赖在 ASP.NET MVC 上)所以你需要同时设置:
ASP.Net Wep.API and ASP.NET MVC uses two different IDependencyResolver
(because they designed the Wep.API to not depend on ASP.NET MVC) so you need to setup both:
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container);
因此需要 AutofacDependencyResolver
将规范注入常规 MVC Controller
派生控制器.
So the AutofacDependencyResolver
is needed to inject decencies to regular MVC Controller
derived controllers.
并且需要 AutofacWebApiDependencyResolver
将依赖项注入 Web.API ApiController
派生控制器.
And the AutofacWebApiDependencyResolver
is needed to inject dependencies to the Web.API ApiController
derived controllers.
并且不要忘记通过调用在您的容器构建器中注册您的 Api 控制器(它不同于通常的 builder.RegisterControllers
方法):
And don't forget to register your Api controllers in your container builder with the call (it differs from usual builder.RegisterControllers
method):
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
这篇关于MVC Web API 不适用于 Autofac 集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!