如何在支持依赖注入的天气NuGet包中使用配置的ApiKey
解决方法:在天气NuGet包中使用配置的ApiKey调用WeatherAPI
1. 修正接口定义
首先调整IGetCurrentWeather接口,补充业务所需的参数,接口本身不包含方法实现:
public interface IGetCurrentWeather { // 接收城市名称,可选温度单位参数(默认摄氏度) Task<string> GetCurrentWeather(string city, string temperatureUnit = "c"); }
2. 创建接口实现类
实现类通过依赖注入获取配置项和HttpClient,避免手动创建实例带来的问题:
public class GetCurrentWeatherService : IGetCurrentWeather { private readonly WeatherOptions _options; private readonly HttpClient _httpClient; // 构造函数注入配置项和HttpClient public GetCurrentWeatherService(IOptions<WeatherOptions> options, HttpClient httpClient) { _options = options.Value; _httpClient = httpClient; } public async Task<string> GetCurrentWeather(string city, string temperatureUnit = "c") { // 校验ApiKey配置 if (string.IsNullOrWhiteSpace(_options.ApiKey)) { throw new InvalidOperationException("未配置WeatherAPI的ApiKey,请通过AddWeatherApi方法设置"); } // 拼接请求URL,使用配置的ApiKey和传入参数 var requestUrl = $"http://api.weatherapi.com/v1/current.json?key={_options.ApiKey}&q={Uri.EscapeDataString(city)}&aqi=no&unit={temperatureUnit}"; var response = await _httpClient.GetAsync(requestUrl); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } }
3. 完善服务注册扩展方法
在扩展方法中完成配置绑定、服务实现注册,同时管理HttpClient生命周期:
public static class WeatherApiServiceCollectionExtensions { public static IServiceCollection AddWeatherApi(this IServiceCollection services, Action<WeatherOptions> configure) { // 绑定配置项 services.Configure(configure); // 注册HttpClient与服务实现的关联 services.AddHttpClient<IGetCurrentWeather, GetCurrentWeatherService>(); return services; } }
4. 项目中使用示例
在目标.NET Core项目的启动逻辑中注册服务后,即可通过依赖注入使用接口,自动读取配置的ApiKey:
// Program.cs(.NET 6+) var builder = WebApplication.CreateBuilder(args); // 注册天气服务并配置ApiKey builder.Services.AddWeatherApi(options => { options.ApiKey = "你的实际ApiKey"; }); var app = builder.Build(); // 示例:在端点中调用服务 app.MapGet("/weather/{city}", async (string city, IGetCurrentWeather weatherService) => { var result = await weatherService.GetCurrentWeather(city); return Results.Ok(result); }); app.Run();
关键注意点
- 不要手动创建
HttpClient:使用DI注入的HttpClient能避免socket资源耗尽问题,AddHttpClient会自动管理其生命周期。 - 依赖
IOptions<WeatherOptions>读取配置:这是.NET Core读取配置的标准方式,支持从appsettings、环境变量、Secret Manager等多来源加载配置。 - 增加参数校验:在实现类中校验ApiKey是否存在,提前暴露配置缺失问题。
内容的提问来源于stack exchange,提问作者mohammed alani
相关产品推荐
相关产品推荐

