1+ using Microsoft . AspNetCore . Hosting . Server ;
2+ using Microsoft . AspNetCore . Hosting . Server . Features ;
3+
4+ var builder = WebApplication . CreateBuilder ( args ) ;
5+ builder . Services . AddHostedService < TestHostedService > ( ) ;
6+ var app = builder . Build ( ) ;
7+
8+ app . MapGet ( "/" , ( ) => "Hello World!" ) ;
9+
10+ app . Run ( ) ;
11+
12+ public class TestHostedService : BackgroundService
13+ {
14+ private readonly IServiceProvider _services ;
15+ private readonly IHostApplicationLifetime _lifetime ;
16+ public TestHostedService ( IServiceProvider services , IHostApplicationLifetime lifetime )
17+ {
18+ _services = services ;
19+ _lifetime = lifetime ;
20+
21+ }
22+
23+ protected override async Task ExecuteAsync ( CancellationToken stoppingToken )
24+ {
25+ if ( ! await WaitForAppStartup ( _lifetime , stoppingToken ) )
26+ {
27+ return ;
28+ }
29+
30+ PrintAddresses ( _services ) ;
31+
32+ _lifetime . StopApplication ( ) ;
33+ }
34+
35+ static async Task < bool > WaitForAppStartup ( IHostApplicationLifetime lifetime , CancellationToken stoppingToken )
36+ {
37+ var startedSource = new TaskCompletionSource ( ) ;
38+ var cancelledSource = new TaskCompletionSource ( ) ;
39+ using var reg1 = lifetime . ApplicationStarted . Register ( ( ) => startedSource . SetResult ( ) ) ;
40+ using var reg2 = stoppingToken . Register ( ( ) => cancelledSource . SetResult ( ) ) ;
41+
42+ Task completedTask = await Task . WhenAny ( startedSource . Task , cancelledSource . Task ) . ConfigureAwait ( false ) ;
43+
44+ return completedTask == startedSource . Task ;
45+ }
46+
47+ void PrintAddresses ( IServiceProvider services )
48+ {
49+ Console . WriteLine ( "Checking addresses..." ) ;
50+ var server = services . GetRequiredService < IServer > ( ) ;
51+ var addressFeature = server . Features . Get < IServerAddressesFeature > ( ) ;
52+ foreach ( var address in addressFeature ! . Addresses )
53+ {
54+ Console . WriteLine ( "Listing on address: " + address ) ;
55+ }
56+ }
57+
58+ }
0 commit comments