如何在需要 DI 的 DNX 中测试自定义中间件?

How to test custom middleware in DNX that required DI?

我正在编写一些自定义中间件以在 ASP.NET 应用程序中使用。 我的中间件依赖于一些服务,我可以使用 AddServices.

方法将这些服务注入到 Microsoft DI 容器中

但是,当使用 xUnit 并创建 TestServer 时,我没有地方调用 Microsoft DI 容器来注入我的中间件所依赖的服务。

有关我如何创建 TestServer 并在其上添加我的中间件的信息,请参见下面的示例:

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

应该在哪里以及如何将我的服务注入 Microsoft DI 容器?

好像比较容易搞定:

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