MVC的Web API与Autofac整合工作 [英] MVC Web API not working with Autofac Integration

查看:343
本文介绍了MVC的Web API与Autofac整合工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC整合从autofac是这样的:

I used the MVC integration from autofac like this:

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

但现在我要重新创建新的Web阿比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.P​​ractices.ServiceLocation.IServiceLocator。

The type Autofac.Integration.WebApi.AutofacWebApiDependencyResolver does not appear to implement 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 控制器导出控制器。

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整合工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆