Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment'

I have the following code which doesnt have any compiler warnings or errors: (its a webjob)

However in the line: builder.Build I got this exception:

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

Code is as follows:

 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

        }
    }
like image 680
Luis Valencia Avatar asked Dec 28 '25 18:12

Luis Valencia


2 Answers

If you're working in donet-isolated environment, I had the same error. I fixed it by using

AddApplicationInsightsTelemetryWorkerService()

from Microsoft.ApplicationInsights.WorkerService instead of Microsoft.ApplicationInsights.AspNetCore

like image 120
wael Avatar answered Dec 31 '25 06:12

wael


Make sure you have a json entry for your instrumentation key in your configuration settings.

{
    "AzureWebJobsStorage": "{storage connection string}",
    "APPINSIGHTS_INSTRUMENTATIONKEY": "{instrumentation key}"
}
like image 29
Ryan Hill - MSFT Avatar answered Dec 31 '25 06:12

Ryan Hill - MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!