From d0ab959c89a0adf6b86d35039b6a91349a5bedd1 Mon Sep 17 00:00:00 2001 From: Brennan Date: Tue, 7 Jul 2020 19:50:31 -0700 Subject: [PATCH] TestServer registers NoopHostLifetime to avoid hangs from not disposing (#23761) --- src/Hosting/TestHost/src/NoopHostLifetime.cs | 22 +++++++++++++++++++ .../TestHost/src/WebHostBuilderExtensions.cs | 2 ++ src/Hosting/TestHost/test/TestServerTests.cs | 15 +++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 src/Hosting/TestHost/src/NoopHostLifetime.cs diff --git a/src/Hosting/TestHost/src/NoopHostLifetime.cs b/src/Hosting/TestHost/src/NoopHostLifetime.cs new file mode 100644 index 0000000000..a449babaae --- /dev/null +++ b/src/Hosting/TestHost/src/NoopHostLifetime.cs @@ -0,0 +1,22 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. + +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; + +namespace Microsoft.AspNetCore.TestHost +{ + internal class NoopHostLifetime : IHostLifetime + { + public Task StopAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + public Task WaitForStartAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + } +} \ No newline at end of file diff --git a/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs b/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs index c2051497cd..ab7db21c5c 100644 --- a/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs +++ b/src/Hosting/TestHost/src/WebHostBuilderExtensions.cs @@ -8,6 +8,7 @@ using System.Net.Http; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; namespace Microsoft.AspNetCore.TestHost { @@ -17,6 +18,7 @@ namespace Microsoft.AspNetCore.TestHost { return builder.ConfigureServices(services => { + services.AddSingleton(); services.AddSingleton(); }); } diff --git a/src/Hosting/TestHost/test/TestServerTests.cs b/src/Hosting/TestHost/test/TestServerTests.cs index d05618cb26..0ffaf8b8b4 100644 --- a/src/Hosting/TestHost/test/TestServerTests.cs +++ b/src/Hosting/TestHost/test/TestServerTests.cs @@ -79,6 +79,21 @@ namespace Microsoft.AspNetCore.TestHost Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } + [Fact] + public async Task UseTestServerRegistersNoopHostLifetime() + { + using var host = await new HostBuilder() + .ConfigureWebHost(webBuilder => + { + webBuilder + .UseTestServer() + .Configure(app => { }); + }) + .StartAsync(); + + Assert.IsType(host.Services.GetService()); + } + [Fact] public void CreateWithDelegate() {