.NET 8独立函数应用集成Application Insights遇键控服务异常求解决
解决.NET 8 Isolated Functions中Application Insights注入的Keyed Services异常
问题场景
我有一个.NET 8 Isolated Functions应用,已为其添加Application Insights,宿主构建器代码如下:
var host = new HostBuilder() .ConfigureFunctionsWebApplication() .ConfigureServices((context, services) => { services.AddApplicationInsightsTelemetryWorkerService(); services.ConfigureFunctionsApplicationInsights(); }) .Build();
执行services.AddApplicationInsightsTelemetryWorkerService();时抛出如下异常:
System.InvalidOperationException HResult=0x80131509 Message=This service descriptor is keyed. Your service provider may not support keyed services. Source=Microsoft.Extensions.DependencyInjection.Abstractions StackTrace: at Microsoft.Extensions.DependencyInjection.ServiceDescriptor.ThrowKeyedDescriptor() in Microsoft.Extensions.DependencyInjection\ServiceDescriptor.cs:line 483
解决方案
1. 移除冗余的服务注册调用
.NET 8 Isolated Functions的ConfigureFunctionsWebApplication()已经自动集成了Application Insights的基础服务配置,无需手动调用AddApplicationInsightsTelemetryWorkerService。仅保留ConfigureFunctionsApplicationInsights()即可,它会负责配置Functions专属的Application Insights参数。
修改后的代码:
var host = new HostBuilder() .ConfigureFunctionsWebApplication() .ConfigureServices((context, services) => { services.ConfigureFunctionsApplicationInsights(); }) .Build();
2. 确保NuGet包版本一致
检查所有与Azure Functions Worker相关的NuGet包(例如Microsoft.Azure.Functions.Worker、Microsoft.Azure.Functions.Worker.ApplicationInsights等)版本是否与.NET 8兼容,且保持版本统一,避免因依赖版本不匹配引发的服务注册冲突。
3. 自定义Application Insights配置(可选)
如果需要对遥测行为进行自定义配置,可以通过Configure<ApplicationInsightsServiceOptions>来设置,示例如下:
var host = new HostBuilder() .ConfigureFunctionsWebApplication() .ConfigureServices((context, services) => { services.ConfigureFunctionsApplicationInsights(); services.Configure<ApplicationInsightsServiceOptions>(options => { // 示例:设置采样率 options.SamplingSettings = new SamplingSettings { IsEnabled = true, MaxTelemetryItemsPerSecond = 5 }; // 其他自定义配置,如禁用特定遥测类型等 }); }) .Build();
内容的提问来源于stack exchange,提问作者Peter Morris
相关产品推荐
相关产品推荐

