Question

Difficulty: MediumConfigure Application Insights Instrumentation and Telemetry

You are developing a C# .NET 8 Azure Function in an isolated worker process. You configure custom telemetry tracking in the function app using Dependency Injection in the `Program.cs` file. However, during runtime, you find that custom telemetry generated via `TelemetryClient` is not being sent to Azure Monitor because the connection string is missing or not bound correctly in the SDK setup.

You have the following code in your `Program.cs` file:

csharp
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices((context, services) =>
{
services.AddApplicationInsightsTelemetryWorkerService(options =>
{
// Line X
});
})
.Build();

await host.RunAsync();

Which of the following lines of code should you insert at `Line X` to correctly bind the connection string from configuration?

  1. options.ConnectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];Answer
  2. B
    options.InstrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
  3. C
    options.InstrumentationKey = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
  4. D
    TelemetryConfiguration.Active.ConnectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];

Answer

options.ConnectionString = context.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"];
The correct option sets the ConnectionString property on the options object using the value retrieved from the host context configuration. This ensures that the Application Insights telemetry client, which is resolved via dependency injection in the Azure Function, has the correct endpoint and key settings to route telemetry to Azure Monitor.

Step-by-Step Solution

1
Identify the target SDK configuration model in .NET 8 worker/function environments.
The SDK relies on ApplicationInsightsServiceOptions registered during AddApplicationInsightsTelemetryWorkerService.
We must configure these options inside the delegate parameter of AddApplicationInsightsTelemetryWorkerService to set the connection string correctly.
2
Choose the correct property name to set.
ConnectionString must be set instead of the deprecated InstrumentationKey property.
Modern Azure Monitor SDKs require ConnectionString to properly support telemetry routing, ingestion endpoints, and security mechanisms.
3
Bind the configuration value from the builder host context.
Access context.Configuration with the key 'APPLICATIONINSIGHTS_CONNECTION_STRING'.
This retrieves the connection string defined in host settings or local settings, ensuring the correct destination is configured.

Key Concept

Azure Monitor Application Insights C# SDK configuration using connection strings and Dependency Injection
Estimated Time:1m 30s
Rate this question