升级netcore2.2到3.1调用AddApplicationInsightsTelemetry报IHostingEnvironment解析错误如何解决
报错信息:System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.AspNetCore.Hosting.DefaultApplicationInsightsServiceConfigureOptions'.'
问题原因
.NET Core 3.0 版本开始,官方将原有的 Microsoft.AspNetCore.Hosting.IHostingEnvironment 接口标记为过时,替换为新的 IWebHostEnvironment 接口,低版本的 Application Insights SDK 仍依赖旧接口,因此会出现服务解析失败的异常。
可行解决方案
方案1(优先推荐):升级 Application Insights 相关 NuGet 包到兼容 .NET Core 3.1 的版本
将Microsoft.ApplicationInsights.AspNetCore包升级到 2.12.0 及以上版本,该版本开始官方已修复对旧宿主环境接口的依赖,升级后直接调用services.AddApplicationInsightsTelemetry();即可正常运行,无需额外修改业务代码。方案2(兼容旧SDK场景):手动注册旧接口的转发实现
如果项目受依赖限制暂时无法升级 Application Insights SDK,可以在调用AddApplicationInsightsTelemetry之前,手动将旧接口映射到当前已注册的新接口实例:
// 需放在 services.AddApplicationInsightsTelemetry(); 之前执行 services.AddSingleton<Microsoft.AspNetCore.Hosting.IHostingEnvironment>(sp => sp.GetRequiredService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>());
额外注意事项
升级过程中建议同步将 Startup 类中所有注入 IHostingEnvironment 的位置替换为 IWebHostEnvironment,避免后续出现其他过时接口相关的报错。
内容的提问来源于stack exchange,提问作者Stuart.Sklinar

