Use IApplicationLifetime instead of a custom token (#1031)

This commit is contained in:
Glenn Condron
2025-10-01 00:21:33 -07:00
committed by GitHub
Unverified
parent 34e03d1e5c
commit 43fe7c6dbe
@@ -40,20 +40,14 @@ builder.Services.AddSingleton<AIAgent>((sp) => new ChatClientAgent(
// Add a sample service that will use the agent to respond to user input.
builder.Services.AddHostedService<SampleService>();
// Create a cancellation token and source to pass to the sample service that can
// be used to signal shutdown of the application.
CancellationTokenSource appShutdownCancellationTokenSource = new();
CancellationToken appShutdownCancellationToken = appShutdownCancellationTokenSource.Token;
builder.Services.AddKeyedSingleton("AppShutdown", appShutdownCancellationTokenSource);
// Build and run the host.
using IHost host = builder.Build();
await host.RunAsync(appShutdownCancellationToken).ConfigureAwait(false);
await host.RunAsync().ConfigureAwait(false);
/// <summary>
/// A sample service that uses an AI agent to respond to user input.
/// </summary>
internal sealed class SampleService(AIAgent agent, [FromKeyedServices("AppShutdown")] CancellationTokenSource appShutdownCancellationTokenSource) : IHostedService
internal sealed class SampleService(AIAgent agent, IHostApplicationLifetime appLifetime) : IHostedService
{
private AgentThread? _thread;
@@ -61,7 +55,7 @@ internal sealed class SampleService(AIAgent agent, [FromKeyedServices("AppShutdo
{
// Create a thread that will be used for the entirety of the service lifetime so that the user can ask follow up questions.
this._thread = agent.GetNewThread();
_ = this.RunAsync(cancellationToken);
_ = this.RunAsync(appLifetime.ApplicationStopping);
}
public async Task RunAsync(CancellationToken cancellationToken)
@@ -78,7 +72,7 @@ internal sealed class SampleService(AIAgent agent, [FromKeyedServices("AppShutdo
// If the user enters no input, signal the application to shut down.
if (string.IsNullOrWhiteSpace(input))
{
appShutdownCancellationTokenSource.Cancel();
appLifetime.StopApplication();
break;
}