Autofac OWIN TestServer and HttpContext

I am trying to set up integration tests with my IIS Hosted WebAPI 2.2 application. I am using Autofac for DI and I am using the new ASP.net Identity stack that OWIN uses. I have a problem with Autofac where the HttpContext class is always null. This is how I set up my base integration test class -

 [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();
    }
}

      

When a simple test runs, I get an ArgumentNullException "The value cannot be null" httpContext. What if I track down the autofile code, I think it comes from this extension method -

 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();
            });
        }
    }

      

remained in the Core / Source / Autofac.Integration.Mvc.Owin / AutofacMvcAppBuilderExtensions.cs file . Is there a problem with my setup or the correct way to use Autofac in integration tests with WebApi application using IIS Host and OWIN Middleware?

+3


source to share


1 answer


It looks like you've already asked this as an issue in the Autofac project . I'll copy / paste the answer here (although in the future it is probably better to go with one or the other rather than both). In the meantime, there is no need to know about it. ”

The great thing about OWIN applications is that you no longer need them HttpContext

. Nothing is attached to it; instead, everything HttpContextBase

and things that are separate from the old IIS. For example, in Web API, the current context is always sent with HttpRequestMessage

- there is no global static HttpContext.Current

, because this is old stuff.

So, when running unit tests with an OWIN test node, you can expect it to not HttpContext.Current

. It separated from it all.

MVC cannot run as OWIN-only because the libraries are tightly coupled with the legacy IIS / ASP.NET stack. Trying to test MVC stuff with OWIN - Only the test server will be frustrating to you. This will change with the new ASP.NET 5.0 with the new Visual Studio.



If you need to test MVC in an integrated way, there is currently no way to do it with OWIN. You must start IIS Express.

Finally, I see that you are missing the Web API middleware for OWIN (the actual Microsoft Web API middleware). This may give you other problems down the line.

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

      

+7


source







All Articles