使用Autofac与ASP.NET Web API RC和ASP.NET MVC3时出错

Mak*_*jer 1 autofac asp.net-mvc-3 asp.net-web-api

我使用NuGet将ASP.NET Web API RC添加到我的MVC3项目中:

Install-Package AspNetWebApi
Run Code Online (Sandbox Code Playgroud)

然后我配置了它.在Global.asax.cs:

// configure regular controllers
var configuration = GlobalConfiguration.Configuration;
var container = Bootstrapper.ConfigureContainer(configuration);
containterProvider = new ContainerProvider(container);
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

// Set the dependency resolver implementation for Web API.
var resolver = new AutofacWebApiDependencyResolver(container);
configuration.DependencyResolver = resolver;
Run Code Online (Sandbox Code Playgroud)

Boostrapper.ConfigureContainer(...)我补充说:

// I register my types as InstancePerLifetimeScope() 
// but I also tried .InstancePerHttpRequest().InstancePerApiRequest()
// to the same end
builder.RegisterType<SomeService>()
    .AsImplementedInterfaces().InstancePerLifetimeScope();
// Register API controllers using assembly scanning.
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);
Run Code Online (Sandbox Code Playgroud)

这里这里描述了一点.

我也更新Autofac,Autofac.Web,Autofac.Mvc3使用的NuGet和已安装的软件包Autofac.WebApi包.

使用此配置,我尝试运行我的ApiController并收到以下错误:

从请求实例的作用域中看不到具有匹配"httpRequest"的标记的作用域.这通常表示注册为每HTTP请求的组件正被SingleInstance()组件(或类似场景)重新请求.在Web集成下,始终从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime请求依赖项,从不从容器本身请求.

然后当我读到Alex Meyer-Gleaves的评论时:

我怀疑您正在使用带有MVC3的Web API包,这导致了问题.在MVC3集成中,InstancePerHttpRequest生命周期范围的标记是"httpRequest".在MVC4测试版和Web API测试包中,我更改了InstancePerHttpRequest和InstancePerApiRequest以使用公共标记"AutofacWebRequest".您可以使用Autofac.Mvc4从NuGet获取MVC4集成包.

有评论的来源文章

所以按照Alex的建议我得到了包,Autofac.Mvc4但它只适用于Mvc4,我的项目不会构建.然后我抓住Autofac的源代码来构建Autofac.Mvc4Mvc3:

hg clone https://code.google.com/p/autofac/ --branch "MVC4 beta" C:\my\path
Run Code Online (Sandbox Code Playgroud)

使用此程序集后,我的引用ApiController开始工作,但常规Controllers只能用于单个控制器操作调用.当视图调用Html.RenderAction(...)时,当我刷新或导航到另一个控制器操作时,它会崩溃并出现此错误:

从请求实例的作用域中看不到具有匹配"AutofacWebRequest"的标记的作用域.这通常表示注册为每HTTP请求的组件正被SingleInstance()组件(或类似场景)重新请求.在Web集成下,始终从DependencyResolver.Current或ILifetimeScopeProvider.RequestLifetime请求依赖项,从不从容器本身请求.

我认为从Autofac.Mvc4针对Mvc3的2.6.2.859版本的最新源代码构建可能有所帮助,但我无法找到它的来源.或者也许这里还有其他问题?

Mak*_*jer 9

我发现了这个问题.我还习惯Autofac.Integration.Web将依赖项注入自定义成员资格和角色提供程序.但是WebLiftime.cs有这条线:

public static readonly object Request = "httpRequest";
Run Code Online (Sandbox Code Playgroud)

一旦我将其更改为:

public static readonly object Request = "AutofacWebRequest";
Run Code Online (Sandbox Code Playgroud)

并使用构建的程序集一切正常,我没有错误:)

我相信这个常数值应该和所有项目一样Autofac.Integration.Web,Autofac.Integration.Mvc并且' Autofac.Integration.WebApi对于Mvc4,所以这应该是一个bug.