当我尝试设置.NET Core WebJob以使用Application Insights时,在启动时出现以下异常:
System.InvalidOperationException:“在尝试激活“ Microsoft.AspNetCore.Hosting.DefaultApplicationInsightsServiceConfigureOptions”时,无法解析类型为“ Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务。”
我确定我正在忽略某些东西,但我找不到它。我的Main方法就像许多示例一样,例如here
public static void Main(string[] args)
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
Configuration.EnvironmentName = environment;
Configuration.IsDevelopment = string.Equals(environment, "Development");
var host = new HostBuilder()
.UseEnvironment("Development")
.ConfigureWebJobs(b =>
{
b.UseHostId("ecad61-62cf-47f4-93b4-6efcded6")
.AddAzureStorageCoreServices()
.AddAzureStorage()
.AddTimers()
.AddEventHubs();
})
.ConfigureServices(x => ConfigureServices(x))
.ConfigureAppConfiguration(b =>
{
b.AddJsonFile("appsettings.json", false, false);
b.AddJsonFile($"appsettings.{environment}.json", true);
b.AddEnvironmentVariables();
Configuration.Config = b.Build();
})
.ConfigureLogging((context, b) =>
{
b.AddConfiguration(Configuration.Config);
b.SetMinimumLevel(LogLevel.Trace);
b.AddConsole();
b.AddDebug();
//TODO fix applicationInsights
string appInsightsKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
if (!string.IsNullOrEmpty(appInsightsKey))
{
b.AddApplicationInsights(o => o.InstrumentationKey = appInsightsKey);
}
})
.Build();
using (host)
{
host.Run();
}
}
答案 0 :(得分:0)
乍一看(并且是黑暗中的真实镜头),我将检查context.Configuration
是否引发异常,因为 APPINSIGHTS_INSTRUMENTATIONKEY 在集合中不存在。丢失的密钥可能引发了一个异常,该异常正在您的DI容器中冒泡。
编辑:尝试尝试此软件包,让我知道是否可行。目前处于预发布状态。 https://www.nuget.org/packages/Microsoft.Extensions.Logging.ApplicationInsights/
编辑:对AddApplicationInsightsTelemetry的调用使用DefaultApplicationInsightsServiceConfigureOptions取决于IHostingEnvironment。 WebJobsSDK未使用IHostingEnvironment,这导致了您的异常。 WebJobsSDK具有Application Insights的用法,您应该能够与https://github.com/Azure/azure-webjobs-sdk/tree/dev/sample/SampleHost示例类似地使用它