Skip to content

Commit 07b46e9

Browse files
mattleibowCopilot
andcommitted
Use IHttpClientFactory instead of singleton HttpClient in WeatherTool
Replace AddSingleton<HttpClient>() with AddHttpClient() in DI registration, and inject IHttpClientFactory into WeatherTool so each request gets a properly managed HttpClient instance with correct handler lifecycle. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 4a2a283 commit 07b46e9

2 files changed

Lines changed: 4 additions & 2 deletions

File tree

10.0/AI/LocalChatClientWithTools/src/MauiProgram.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ public static MauiApp CreateMauiApp()
2727
builder.Services.AddSingleton<MainPage>();
2828

2929
// Register tool services
30-
builder.Services.AddSingleton<HttpClient>();
30+
builder.Services.AddHttpClient();
3131
builder.Services.AddSingleton<CalculatorTool>();
3232
builder.Services.AddSingleton<WeatherTool>();
3333
builder.Services.AddSingleton<FileOperationsTool>();

10.0/AI/LocalChatClientWithTools/src/Services/Tools/WeatherTool.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
namespace LocalChatClientWithTools.Services.Tools;
77

8-
public partial class WeatherTool(HttpClient httpClient)
8+
public partial class WeatherTool(IHttpClientFactory httpClientFactory)
99
{
1010
public static AIFunction CreateAIFunction(IServiceProvider services)
1111
=> AIFunctionFactory.Create(
@@ -24,6 +24,8 @@ public async Task<WeatherResult> GetWeatherAsync(
2424

2525
try
2626
{
27+
using var httpClient = httpClientFactory.CreateClient();
28+
2729
var geoUrl = $"https://geocoding-api.open-meteo.com/v1/search?name={Uri.EscapeDataString(location)}&count=1";
2830
using var geoResponse = await httpClient.GetAsync(geoUrl, cancellationToken);
2931
geoResponse.EnsureSuccessStatusCode();

0 commit comments

Comments
 (0)