Solved: Azure Functions in Azure Container Apps - Unable to resolve service for type IHostingEnvironment while attempting to activate DefaultApplicationInsightsServiceConfigureOptions

As mentioned in my previous post I am currently switching my wife's eshop from Azure App Services to Azure Container Apps. The solution itself uses an Azure Functions project to perform asynchronous operations triggered via queued messages and uses Azure Application Insights for logging and monitoring.

The Problem

The previous functions project I had was initialising Application Insights using the AddApplicationInsightsTelemetry configuration function of the Microsoft.ApplicationInsights.AspNetCore nuget package and it used to work without issues.

I setup my host startup as per the below:

    var host = new HostBuilder()
        .ConfigureFunctionsWorkerDefaults()
        .ConfigureServices((hostContext, services) =>
        {
            services.AddApplicationInsightsTelemetry();
            services.AddCloudRoleNameInitializer("Functions");
        })
        .Build();


    host.Run();

However, I started getting the following Exception "Unable to resolve service for type 'Microsoft.AspNetCore.Hosting.IHostingEnvironment' while attempting to activate 'Microsoft.AspNetCore.Hosting.DefaultApplicationInsightsServiceConfigureOptions'" during startup of the app.

Unable to resolve service for type error screenshot

The Solution

Through various google searches I managed to figure out that the Azure Functions host sets up Application Insights itself so that it can instrument the host and this functionality is incompatible with the registration of Application Insights via the method I was using. Luckily the solution is trivial to implement as one just needs to add an environment variable in the Docker file or in the Environment variables section of the Container App.

The environment variable name to be added should be named APPINSIGHTS_INSTRUMENTATIONKEY and populated with the Instrumentation Key obtained from the Azure portal (Guid only).

Once this is done the application starts up correctly and you will start receiving telemetry in your Application Insights.