Asp.net Autofac OWIN TestServer和HttpContext

Asp.net Autofac OWIN TestServer和HttpContext,asp.net,asp.net-mvc-5,integration-testing,autofac,asp.net-web-api2,Asp.net,Asp.net Mvc 5,Integration Testing,Autofac,Asp.net Web Api2,我正在尝试使用IIS托管的WebAPI 2.2应用程序设置集成测试。我使用Autofac for DI,并使用使用OWIN的新ASP.net标识堆栈。我遇到了Autofac的一个问题,其中HttpContext类始终为null。下面是我如何设置我的基本集成测试类- [TestClass] public class TestBase { private SimpleLifetimeScopeProvider _scopeProvider; private IDependencyR

我正在尝试使用IIS托管的WebAPI 2.2应用程序设置集成测试。我使用Autofac for DI,并使用使用OWIN的新ASP.net标识堆栈。我遇到了Autofac的一个问题,其中HttpContext类始终为null。下面是我如何设置我的基本集成测试类-

 [TestClass]
public class TestBase
{
    private SimpleLifetimeScopeProvider _scopeProvider;
    private IDependencyResolver _originalResolver;
    private HttpConfiguration _configuration;
    public TestServer Server { get; private set; }

    [TestInitialize]
    public void Setup()
    {
        Server = TestServer.Create(app =>
        {
            //config webpai
            _configuration = new HttpConfiguration();
            WebApiConfig.Register(_configuration);

            // Build the container.
            var container = App_Start.IocConfig.RegisterDependencies(_configuration);
            _scopeProvider = new SimpleLifetimeScopeProvider(container);

            //set the mvc dep resolver
            var mvcResolver = new AutofacDependencyResolver(container, _scopeProvider);
            _originalResolver = DependencyResolver.Current;
            DependencyResolver.SetResolver(mvcResolver);

            //set the webapi dep resolvers
            _configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(_configuration);
            app.UseAutofacMvc();
        });
    }

    [TestCleanup]
    public void Cleanup()
    {
        // Clean up the fake 'request' scope.
        _configuration.Dispose();
        DependencyResolver.SetResolver(_originalResolver);
        _scopeProvider.EndLifetimeScope();
        Server.Dispose();
    }
}
当一个简单的测试开始时,我得到一个ArgumentNullException“Value cannot be null”httpContext。如果我追踪到autofac代码,我认为它来自这个扩展方法-

 public static class AutofacMvcAppBuilderExtensions
    {
        internal static Func<HttpContextBase> CurrentHttpContext = () => new HttpContextWrapper(HttpContext.Current);

        /// <summary>
        /// Extends the Autofac lifetime scope added from the OWIN pipeline through to the MVC request lifetime scope.
        /// </summary>
        /// <param name="app">The application builder.</param>
        /// <returns>The application builder.</returns>
        [SecuritySafeCritical]
        [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public static IAppBuilder UseAutofacMvc(this IAppBuilder app)
        {
            return app.Use(async (context, next) =>
            {
                var lifetimeScope = context.GetAutofacLifetimeScope();
                var httpContext = CurrentHttpContext();

                if (lifetimeScope != null && httpContext != null)
                    httpContext.Items[typeof(ILifetimeScope)] = lifetimeScope;

                await next();
            });
        }
    }
public静态类AutofacMvcAppBuilderExtensions
{
内部静态函数CurrentHttpContext=()=>新的HttpContextWrapper(HttpContext.Current);
/// 
///将从OWIN管道添加的Autofac生存期范围扩展到MVC请求生存期范围。
/// 
///应用程序生成器。
///应用程序生成器。
[安全性安全关键]
[SuppressMessage(“Microsoft.Reliability”,“CA2000:在失去作用域之前处理对象”)]
公共静态IAppBuilder UseAutofacMvc(此IAppBuilder应用程序)
{
返回app.Use(异步(上下文,下一步)=>
{
var lifetimeScope=context.GetAutofacLifetimeScope();
var httpContext=CurrentHttpContext();
if(lifetimeScope!=null&&httpContext!=null)
httpContext.Items[typeof(ILifetimeScope)]=生命周期;
等待下一个();
});
}
}

在文件中被删除。我的设置是否有问题,或者在与使用IIS主机和OWIN中间件的WebApi应用程序的集成测试中使用Autofac是否有正确的方法

看来你已经问过了。我将把答案复制/粘贴到这里(不过将来可能最好选择其中一个,而不是两个)

OWIN-only应用程序的一部分惊人之处在于,您不再需要
HttpContext
。没有什么与此相关;取而代之的是所有的
HttpContextBase
以及与传统IIS分离的东西。就像在Web API中一样,当前上下文总是随
HttpRequestMessage
一起发送-没有全局静态
HttpContext.current
,因为这是遗留内容

因此,当您使用OWIN测试主机运行单元测试时,可以预期不会出现
HttpContext.Current
。它与所有这些都是分离的

尝试使用仅OWIN的测试服务器来测试MVC内容会给您带来这样的麻烦。随着新的Visual Studio推出新的ASP.NET 5.0,这种情况将发生变化

如果您需要以集成的方式测试MVC,那么目前还没有一种方法可以使用OWIN进行测试。你必须启动IIS Express

最后,我确实看到您缺少OWIN的Web API中间件(实际的Microsoft Web API中间件)。这可能会给你带来其他问题

app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(_configuration);
app.UseAutofacMvc();
// You're missing this:
app.UseWebApi(config);

特拉维斯,谢谢你的回复。很抱歉重复发布,我将坚持在未来的autofac回购。我认为我的问题可能源于我的总体架构。该应用程序主要是一个Web API项目,将OWIN用于ASP.net标识库。然而,我们确实有一些传统的MVC控制器,在某些路由上提供Razor视图。WebApi和MVC控制器都注入了一些相同的依赖项。听起来我应该将MVC控制器转移到另一个项目中,以实现最简单的集成测试场景。