Skip to content

Commit d0ab959

Browse files
TestServer registers NoopHostLifetime to avoid hangs from not disposing (#23761)
1 parent 3709eda commit d0ab959

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
using System.Threading;
5+
using System.Threading.Tasks;
6+
using Microsoft.Extensions.Hosting;
7+
8+
namespace Microsoft.AspNetCore.TestHost
9+
{
10+
internal class NoopHostLifetime : IHostLifetime
11+
{
12+
public Task StopAsync(CancellationToken cancellationToken)
13+
{
14+
return Task.CompletedTask;
15+
}
16+
17+
public Task WaitForStartAsync(CancellationToken cancellationToken)
18+
{
19+
return Task.CompletedTask;
20+
}
21+
}
22+
}

src/Hosting/TestHost/src/WebHostBuilderExtensions.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Microsoft.AspNetCore.Hosting;
99
using Microsoft.AspNetCore.Hosting.Server;
1010
using Microsoft.Extensions.DependencyInjection;
11+
using Microsoft.Extensions.Hosting;
1112

1213
namespace Microsoft.AspNetCore.TestHost
1314
{
@@ -17,6 +18,7 @@ public static IWebHostBuilder UseTestServer(this IWebHostBuilder builder)
1718
{
1819
return builder.ConfigureServices(services =>
1920
{
21+
services.AddSingleton<IHostLifetime, NoopHostLifetime>();
2022
services.AddSingleton<IServer, TestServer>();
2123
});
2224
}

src/Hosting/TestHost/test/TestServerTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,21 @@ public async Task GenericCreateAndStartHost_GetTestClient()
7979
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
8080
}
8181

82+
[Fact]
83+
public async Task UseTestServerRegistersNoopHostLifetime()
84+
{
85+
using var host = await new HostBuilder()
86+
.ConfigureWebHost(webBuilder =>
87+
{
88+
webBuilder
89+
.UseTestServer()
90+
.Configure(app => { });
91+
})
92+
.StartAsync();
93+
94+
Assert.IsType<NoopHostLifetime>(host.Services.GetService<IHostLifetime>());
95+
}
96+
8297
[Fact]
8398
public void CreateWithDelegate()
8499
{

0 commit comments

Comments
 (0)