44using Microsoft . Extensions . Hosting ;
55using Microsoft . Extensions . Logging ;
66
7+ // ReSharper disable MemberCanBePrivate.Global - public API
78namespace CodeCaster . WindowsServiceExtensions
89{
910 /// <summary>
1011 /// Terminates the host application when an exception occurs in <see cref="ExecuteAsync"/>.
1112 /// </summary>
1213 public abstract class HostTerminatingBackgroundService : BackgroundService
1314 {
14- private readonly ILogger < HostTerminatingBackgroundService > _logger ;
15- private readonly IHostApplicationLifetime _applicationLifetime ;
15+ /// <summary>
16+ /// Logs.
17+ /// </summary>
18+ protected readonly ILogger < HostTerminatingBackgroundService > Logger ;
19+
20+ /// <summary>
21+ /// To ask nicely to stop the host when cancellation is requested. We're just a BackgroundService, returning from ExecuteAsync() won't stop the host application. Better us than Windows.
22+ /// </summary>
23+ protected readonly IHostApplicationLifetime ApplicationLifetime ;
1624
1725 /// <inheritdoc/>
1826 protected HostTerminatingBackgroundService ( ILogger < HostTerminatingBackgroundService > logger , IHostApplicationLifetime applicationLifetime )
1927 {
20- _logger = logger ;
21- _applicationLifetime = applicationLifetime ;
28+ Logger = logger ;
29+ ApplicationLifetime = applicationLifetime ;
2230 }
2331
2432 /// <inheritdoc />
@@ -32,13 +40,13 @@ protected sealed override async Task ExecuteAsync(CancellationToken stoppingToke
3240 {
3341 var errorString = $ "Unhandled exception in { GetType ( ) . FullName } .ExecuteAsync()";
3442
35- _logger . LogError ( e , errorString ) ;
43+ Logger . LogError ( e , errorString ) ;
3644
3745 // .NET 6+ terminates the host on exception, 5 doesn't. Do it ourselves.
3846 // https://docs.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/hosting-exception-handling
3947 Environment . ExitCode = - 1 ;
4048
41- _applicationLifetime . StopApplication ( ) ;
49+ ApplicationLifetime . StopApplication ( ) ;
4250
4351 throw new InvalidOperationException ( errorString , e ) ;
4452 }
0 commit comments