Search code examples
asp.netdependency-injectiondnx

How to test custom middleware in DNX that required DI?


I'm writing some custom Middleware to use in an ASP.NET application. My middleware depends on some services which I can inject in the Microsoft DI container using the method AddServices.

However, when using xUnit and creating a TestServer, I have no place to call the Microsoft DI container to inject my services that my middleware depends on.

See the example below for information on how I create a TestServer and add my Middleware on it:

/// <summary>
///     Create a server with the ASP.NET Core Logging Middleware registered without any configuration.
///     The server will throw an exception of type <typeparamref name="T"/> on every request.
/// </summary>
/// <typeparam name="T">The type of exception to throw.</typeparam>
/// <returns>A <see cref="TestServer"/> that can be used to unit test the middleware.</returns>
private TestServer CreateServerWithAspNetCoreLogging<T>()
    where T : Exception, new()
{
    return TestServer.Create(app =>
    {
        app.UseAspNetCoreLogging();

        SetupTestServerToThrowOnEveryRequest<T>(app);
    });
}

Where and how should inject my services into the Microsoft DI container?


Solution

  • Seems that it can be done relatively easily:

    /// <summary>
    ///     Create a server with the ASP.NET Core Logging Middleware registered without any configuration.
    ///     The server will throw an exception of type <typeparamref name="T"/> on every request.
    /// </summary>
    /// <typeparam name="T">The type of exception to throw.</typeparam>
    /// <returns>A <see cref="TestServer"/> that can be used to unit test the middleware.</returns>
    private TestServer CreateServerWithAspNetCoreLogging<T>()
        where T : Exception, new()
    {
        return TestServer.Create(null, app =>
        {
            app.UseAspNetCoreLogging<string>();
    
            SetupTestServerToThrowOnEveryRequest<T>(app);
        }, services =>
        {
            services.AddAspNetCoreLogging();
        });
    }