diff --git a/dotnet/samples/GettingStarted/Agents/Agent_Step09_DependencyInjection/Program.cs b/dotnet/samples/GettingStarted/Agents/Agent_Step09_DependencyInjection/Program.cs index 93608bb0ed..6db03bd5d8 100644 --- a/dotnet/samples/GettingStarted/Agents/Agent_Step09_DependencyInjection/Program.cs +++ b/dotnet/samples/GettingStarted/Agents/Agent_Step09_DependencyInjection/Program.cs @@ -40,20 +40,14 @@ builder.Services.AddSingleton((sp) => new ChatClientAgent( // Add a sample service that will use the agent to respond to user input. builder.Services.AddHostedService(); -// 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); /// /// A sample service that uses an AI agent to respond to user input. /// -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; }