Skip to content

Commit 03213fc

Browse files
committed
Refactor HostApplicationLifetime retrieval and registration
Simplified and improved the retrieval and registration of the HostApplicationLifetime service in BotApp.cs and BotBuilder.cs. In BotApp.cs, the code now retrieves IHostApplicationLifetime and casts it to HostApplicationLifetime, throwing an InvalidOperationException if the cast fails. In BotBuilder.cs, the registration of HostApplicationLifetime has been simplified by removing the factory method and directly registering the service. These changes enhance the robustness and clarity of the code.
1 parent 5ab4360 commit 03213fc

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

Sources/TelegramBot/BotApp.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,8 @@ public async Task StartAsync(CancellationToken cancellationToken = default)
122122
await hostedService.StartAsync(mergedToken);
123123
_logger.LogInformation("Started '{hostedService}'.", hostedService.GetType().Name);
124124
}
125-
var hostApplicationLifetime = _serviceProvider.GetRequiredService<HostApplicationLifetime>();
125+
var hostApplicationLifetime = _serviceProvider.GetRequiredService<IHostApplicationLifetime>()
126+
as HostApplicationLifetime ?? throw new InvalidOperationException("Host application lifetime is not registered.");
126127
hostApplicationLifetime.NotifyStarted();
127128
}
128129

@@ -141,7 +142,8 @@ public async Task StopAsync(CancellationToken cancellationToken = default)
141142
{
142143
CheckDisposed();
143144
_logger.LogInformation("Stopping hosted services...");
144-
var hostApplicationLifetime = _serviceProvider.GetRequiredService<HostApplicationLifetime>();
145+
var hostApplicationLifetime = _serviceProvider.GetRequiredService<IHostApplicationLifetime>()
146+
as HostApplicationLifetime ?? throw new InvalidOperationException("Host application lifetime is not registered.");
145147
hostApplicationLifetime.NotifyStopping();
146148
var hostedServices = _serviceProvider.GetServices<IHostedService>();
147149
List<Task> tasks = new List<Task>();

Sources/TelegramBot/Builders/BotBuilder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ public IBot Build()
140140
{
141141
Services.AddSingleton<IKeyValueProvider, InMemoryKeyValueProvider>();
142142
}
143-
Services.AddSingleton<IHostApplicationLifetime, HostApplicationLifetime>(x => new HostApplicationLifetime());
143+
Services.AddSingleton<IHostApplicationLifetime, HostApplicationLifetime>();
144144
return new BotApp(client, Services.BuildServiceProvider());
145145
}
146146
}

0 commit comments

Comments
 (0)