Skip to content

Commit

Permalink
Resolving TelemetryClient in ActivitySourceDependencyCollector sh…
Browse files Browse the repository at this point in the history
…ould be on need (#252)

`IHostedService` implementations may be invoked before the `TelemetryClient` is available. This change makes it possible to use `ActivitySourceDependencyCollector` in such scenarios instead of crashing.
  • Loading branch information
mburumaxwell authored May 16, 2024
1 parent ccc4c18 commit 31d7735
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Diagnostics;

Expand All @@ -8,13 +9,13 @@ namespace Tingle.AspNetCore.ApplicationInsights;
// See https://github.com/microsoft/ApplicationInsights-dotnet/issues/1427
internal class ActivitySourceDependencyCollector : IHostedService
{
private readonly TelemetryClient client;
private readonly IServiceProvider serviceProvider;
private readonly IDictionary<string, ActivitySamplingResult> activities;
private readonly ActivityListener? listener;

public ActivitySourceDependencyCollector(TelemetryClient client, IDictionary<string, ActivitySamplingResult> activities)
public ActivitySourceDependencyCollector(IServiceProvider serviceProvider, IDictionary<string, ActivitySamplingResult> activities)
{
this.client = client ?? throw new ArgumentNullException(nameof(client));
this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
this.activities = activities ?? throw new ArgumentNullException(nameof(activities));

if (activities.Count > 0)
Expand All @@ -34,6 +35,9 @@ public ActivitySourceDependencyCollector(TelemetryClient client, IDictionary<str

internal void ActivityStopped(Activity activity)
{
var client = serviceProvider.GetService<TelemetryClient>();
if (client is null) return;

// extensibility point - can chain more telemetry extraction methods here
var telemetry = ExtractDependencyTelemetry(activity);
if (telemetry == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,6 @@ public static IServiceCollection AddActivitySourceDependencyCollector(this IServ
public static IServiceCollection AddActivitySourceDependencyCollector(this IServiceCollection services,
IDictionary<string, ActivitySamplingResult> activities)
{
return services.AddHostedService(p => ActivatorUtilities.CreateInstance<ActivitySourceDependencyCollector>(p, [activities]));
return services.AddHostedService(p => new ActivitySourceDependencyCollector(p, activities));
}
}

0 comments on commit 31d7735

Please sign in to comment.