// in Program.cs
builder.Services.AddSingleton<IWeatherClient, OpenWeatherClient>();
builder.Services.AddHttpClient("openWeatherApi", client =>
{
client.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/");
});
// in OpenWeatherClient.cs
public class OpenWeatherClient : IWeatherClient
{
private const string OpenWeatherMapApiKey = "";
private readonly IHttpClientFactory _httpClientFactory;
public OpenWeatherClient(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<WeatherResponse?> GetCurrentWeatherForCity(string city)
{
var client = _httpClientFactory.CreateClient("openWeatherApi");
return await client.GetFromJsonAsync<WeatherResponse>(
$"weather?q={city}&appid={OpenWeatherMapApiKey}");
}
}
// in Program.cs
builder.Services.AddHttpClient<IWeatherClient, OpenWeatherClient>(client =>
{
client.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/");
});
// in OpenWeatherClient.cs
public class OpenWeatherClient : IWeatherClient
{
private const string OpenWeatherMapApiKey = "";
private readonly HttpClient _httpClient;
public OpenWeatherClientSecond(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<WeatherResponse?> GetCurrentWeatherForCity(string city)
{
return await _httpClient.GetFromJsonAsync<WeatherResponse>(
$"weather?q={city}&appid={OpenWeatherMapApiKey}");
}
}