OlavT
OlavT

Reputation: 2666

How to pass connection string to Application Insights?

I have a .NET Core 3.1 console application and would like to configure it using a connection string specified in appsettings.json.

This is the code for a test app:

static void Main(string[] args)
{
    var configurationBuilder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddEnvironmentVariables();

    // To be able to read configuration from .json files
    var configuration = configurationBuilder.Build();

    // Create the DI container.
    IServiceCollection services = new ServiceCollection();

    services.AddApplicationInsightsTelemetryWorkerService();

    // Build ServiceProvider.
    IServiceProvider serviceProvider = services.BuildServiceProvider();

    // Obtain TelemetryClient instance from DI, for additional manual tracking or to flush.
    var telemetryClient = serviceProvider.GetRequiredService<TelemetryClient>();

    telemetryClient.TrackTrace("Hello, world 3!");

    // Explicitly call Flush() followed by sleep is required in Console Apps.
    // This is to ensure that even if application terminates, telemetry is sent to the back-end.
    telemetryClient.Flush();
    Task.Delay(5000).Wait();
}

The problem is that it seems like Application Insight is not picking up the connection string. I do not see any Trace messages in Application Insights. If I pass the instrumentation key to AddApplicationInsightsTelemetryWorkerService it works.

This is the content of appsettings.json:

{
  "ApplicationInsights": {
    "ConnectionString": "<my connection string>"
  }
}

What am I missing?

Upvotes: 1

Views: 8709

Answers (1)

I don't know if the issue is still exist, but you can pass the Connection String straight to the TelemetryConfiguration.

var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.ConnectionString = Configuration["AzureApplicationInsightsConnectionString"];

Or, you can add it to the servicecollection:

var options = new ApplicationInsightsServiceOptions { ConnectionString = Configuration["AzureApplicationInsightsConnectionString"] };
services.AddApplicationInsightsTelemetry(options: options);

Upvotes: 5

Related Questions