public static IServiceCollection AddApplicationInsightsTelemetryClient(this IServiceCollection builder, IConfiguration config, string serviceName, TelemetryChannelType channelType = TelemetryChannelType.Default) { Guard.ArgumentNotNull(config, nameof(config)); ApplicationInsightsOptions appInsightsOptions = new ApplicationInsightsOptions(); config.Bind("ApplicationInsightsOptions", appInsightsOptions); string appInsightsKey = appInsightsOptions.InstrumentationKey; if (string.IsNullOrWhiteSpace(appInsightsKey)) { throw new InvalidOperationException("Unable to lookup Application Insights Configuration key from Configuration Provider. The value returned was empty string"); } TelemetryConfiguration appInsightsTelemetryConfiguration = TelemetryConfiguration.Active; appInsightsTelemetryConfiguration.InstrumentationKey = appInsightsKey; if (channelType == TelemetryChannelType.Sync) { appInsightsTelemetryConfiguration.TelemetryChannel = new SyncTelemetryChannel(appInsightsOptions.Url); } TelemetryClient telemetryClient = new TelemetryClient(appInsightsTelemetryConfiguration); telemetryClient.InstrumentationKey = appInsightsKey; if (!telemetryClient.Context.GlobalProperties.ContainsKey(LoggingConstants.ServiceNamePropertiesName)) { telemetryClient.Context.GlobalProperties.Add(LoggingConstants.ServiceNamePropertiesName, serviceName); } builder.AddSingleton(telemetryClient); return(builder); }
public static IServiceCollection AddApplicationInsightsTelemetryClient(this IServiceCollection builder, IConfiguration config, string serviceName, TelemetryChannelType channelType = TelemetryChannelType.Default) { Guard.ArgumentNotNull(config, nameof(config)); ApplicationInsightsOptions appInsightsOptions = new ApplicationInsightsOptions(); config.Bind("ApplicationInsightsOptions", appInsightsOptions); string appInsightsKey = appInsightsOptions.InstrumentationKey; if (string.IsNullOrWhiteSpace(appInsightsKey)) { throw new InvalidOperationException("Unable to lookup Application Insights Configuration key from Configuration Provider. The value returned was empty string"); } builder.Configure((ApplicationInsightsServiceOptions options) => options.InstrumentationKey = appInsightsKey); if (channelType == TelemetryChannelType.Sync) { builder.AddSingleton(typeof(ITelemetryChannel), new SyncTelemetryChannel(appInsightsOptions.Url)); } //builder.AddApplicationInsightsTelemetry(config); builder.AddScoped((ctx) => { TelemetryConfiguration telemetryConfiguration = ctx.GetService <TelemetryConfiguration>(); TelemetryClient client = new TelemetryClient(telemetryConfiguration) { InstrumentationKey = appInsightsKey }; if (!client.Context.GlobalProperties.ContainsKey(LoggingConstants.ServiceNamePropertiesName)) { client.Context.GlobalProperties.Add(LoggingConstants.ServiceNamePropertiesName, serviceName); } return(client); }); return(builder); }