System.InvalidOperationException:“无法解析类型“Microsoft.AspNetCore.Hosting.IHostingEnvironment”的服务

Lui*_*cia 11 .net c# asp.net azure-webjobs azure-application-insights

我有以下代码,没有任何编译器警告或错误:(它是一个网络作业)

然而,在行: builder.Build 我得到了这个异常:

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.AspNetCore.Hosting.DefaultApplicationInsightsServiceConfigureOptions
Run Code Online (Sandbox Code Playgroud)

代码如下:

 public class Program
    {
        private static IConfiguration Configuration { get; set; }
        static async Task Main(string[] args)
        {
            var builder = new HostBuilder();
            builder.ConfigureWebJobs(b =>
            {
                b.AddAzureStorageCoreServices();
                b.AddAzureStorage();
                b.AddTimers();
                b.AddServiceBus(sbOptions =>
                {
                    sbOptions.ConnectionString = Configuration["AzureWebJobsServiceBus"];
                });
            });

            builder.ConfigureServices((context, s) => { ConfigureServices(s); s.BuildServiceProvider(); });
            builder.ConfigureLogging(logging =>
            {
                string appInsightsKey = Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
                if (!string.IsNullOrEmpty(appInsightsKey))
                {
                    // This uses the options callback to explicitly set the instrumentation key.
                    logging.AddApplicationInsights(appInsightsKey)
                            .SetMinimumLevel(LogLevel.Information);
                    logging.AddApplicationInsightsWebJobs(o => { o.InstrumentationKey = appInsightsKey; });
                }

            });
            var tokenSource = new CancellationTokenSource();
            CancellationToken ct = tokenSource.Token;
            var host = builder.Build();
            using (host)
            {
                await host.RunAsync(ct);
                tokenSource.Dispose();
            }
        }

        private static void ConfigureServices(IServiceCollection services)
        {
            var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

            Configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables() //this doesnt do anything useful notice im setting some env variables explicitly. 
                .Build();  //build it so you can use those config variables down below.

            Environment.SetEnvironmentVariable("QueueToIndexDocumentsFrom", Configuration["QueueToIndexDocumentsFrom"]);
            Environment.SetEnvironmentVariable("SearchServiceName", Configuration["SearchServiceName"]);
            Environment.SetEnvironmentVariable("SearchServideAdminApiKey", Configuration["SearchServideAdminApiKey"]);
            Environment.SetEnvironmentVariable("SearchServiceIndexClientDocuments", Configuration["SearchServiceIndexClientDocuments"]);
            Environment.SetEnvironmentVariable("SearchServiceIndexJobDocuments", Configuration["SearchServiceIndexJobDocuments"]);
            Environment.SetEnvironmentVariable("SearchServiceIndexBillCycleDocuments", Configuration["SearchServiceIndexBillCycleDocuments"]);

            #region RegisterServiceProviders
                services.AddSingleton(Configuration);
                services.AddScoped<Functions, Functions>();
                services.AddScoped<IIndexer, Indexer>();
                services.AddApplicationInsightsTelemetry();
            #endregion

        }
    }
Run Code Online (Sandbox Code Playgroud)

小智 21

如果您在 donet 隔离环境中工作,我也会遇到同样的错误。我通过使用修复了它

AddApplicationInsightsTelemetryWorkerService()
Run Code Online (Sandbox Code Playgroud)

来自Microsoft.ApplicationInsights.WorkerService而不是Microsoft.ApplicationInsights.AspNetCore


Rya*_*SFT 4

确保您的配置设置中有一个用于检测密钥的 json 条目。

{
    "AzureWebJobsStorage": "{storage connection string}",
    "APPINSIGHTS_INSTRUMENTATIONKEY": "{instrumentation key}"
}
Run Code Online (Sandbox Code Playgroud)