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

问题描述 投票:0回答:1

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

但是在该行中:builder.Build我遇到了这个例外:

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.AspNetCore.Hosting.DefaultApplicationInsightsServiceConfigureOptions

代码如下:

 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

        }
    }
c# asp.net .net azure-application-insights azure-webjobs
1个回答
0
投票

确保您在configuration settings中有一个用于仪表键的json条目。

{
    "AzureWebJobsStorage": "{storage connection string}",
    "APPINSIGHTS_INSTRUMENTATIONKEY": "{instrumentation key}"
}
© www.soinside.com 2019 - 2024. All rights reserved.