Azure函数进程内模型中配置服务与Typed HttpClient的正确方法
问题:Azure函数进程内模型中配置Typed HttpClient读取Options
在使用.NET进程内模型的Azure函数应用的Startup.cs中配置服务时,已在local.settings.json(及Azure托管环境)配置以下参数:
"MyOptions:BaseAddress": "https://dev.azurewebsites.net/api/", "MyOptions:Scope": "xxx/.default",
通过扩展方法完成Options的配置:
private static IServiceCollection AddOptions(this IServiceCollection services) { return services.AddOptions<MyOptions>() .Configure<IConfiguration>((settings, configuration) => { configuration.GetSection(nameof(MyOptions)).Bind(settings); }) .PostConfigure(opt => opt.ThrowIfValuesNotSet()) .Services; }
配置完Options后,希望配置Typed HttpClient时使用其中的BaseAddress,但不清楚如何实现,目前只能直接读取环境变量,不依赖配置类:
var baseAddress = new Uri(Environment.GetEnvironmentVariable($"{nameof(MyOptions)}:BaseAddress"));
对应的HttpClient配置代码如下(待填充BaseAddress):
services .AddOptions() .AddHttpClient<IMyService, MyService>(client => { client.BaseAddress = <value from options>; } )
后续在委托处理器中使用相同Options管理被调用服务的授权时,依赖注入可以正常工作:
public class MyAuthorizationHandler : DelegatingHandler { private readonly TokenCredential _credential; private readonly MyOptions _options; public MyAuthorizationHandler(TokenCredential credential, IOptions<MyOptions> options) { _credential = credential; _options = options.Value; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var token = await _credential.GetTokenAsync( new TokenRequestContext(new[] { _options.Scope }), cancellationToken); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token); return await base.SendAsync(request, cancellationToken); } }
已知可以从IFunctionsHostBuilder获取IConfiguration,但遵循IServiceCollection扩展方法的模式时,传递IConfiguration实例较为繁琐,求推荐实现方式。
更新AddHttpClient存在支持获取服务提供者的重载,可通过该重载读取已配置的Options:
.AddHttpClient<IMyService, MyService>((provider, client) => { client.BaseAddress = new Uri(provider.GetRequiredService<MyOptions>().BaseAddress); })
内容的提问来源于stack exchange,提问作者jokarl
相关产品推荐
相关产品推荐

