Skip to content

Commit

Permalink
Remove AddSingletonIfNotExists and call TryAddSingleton to fix bugs w…
Browse files Browse the repository at this point in the history
…hen keyed services are registered.
  • Loading branch information
CodeBlanch committed Oct 22, 2024
1 parent e34286b commit 55b8e03
Show file tree
Hide file tree
Showing 6 changed files with 133 additions and 193 deletions.
22 changes: 1 addition & 21 deletions NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,26 +280,6 @@ internal static void AddTelemetryConfiguration(
}
}

/// <summary>
/// The AddSingleton method will not check if a class has already been added as an ImplementationType.
/// This extension method is to encapsulate those checks.
/// </summary>
/// <remarks>
/// Must check all three properties to avoid duplicates or null ref exceptions.
/// </remarks>
/// <typeparam name="TService">The type of the service to add.</typeparam>
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
/// <param name="services">The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the service to.</param>
internal static void AddSingletonIfNotExists<TService, TImplementation>(this IServiceCollection services)
where TService : class
where TImplementation : class, TService
{
if (!services.Any(o => o.ImplementationFactory == null && typeof(TImplementation).IsAssignableFrom(o.ImplementationType ?? o.ImplementationInstance.GetType())))
{
services.AddSingleton<TService, TImplementation>();
}
}

private static bool TryGetValue(this IConfiguration config, string primaryKey, out string value, string backupKey = null)
{
value = config[primaryKey];
Expand Down Expand Up @@ -332,7 +312,7 @@ private static void AddCommonInitializers(IServiceCollection services)
private static void AddCommonTelemetryModules(IServiceCollection services)
{
// Previously users were encouraged to manually add the DiagnosticsTelemetryModule.
services.AddSingletonIfNotExists<ITelemetryModule, DiagnosticsTelemetryModule>();
services.TryAddSingleton<ITelemetryModule, DiagnosticsTelemetryModule>();

// These modules add properties to Heartbeat and expect the DiagnosticsTelemetryModule to be configured in DI.
services.AddSingleton<ITelemetryModule, AppServicesHeartbeatTelemetryModule>();
Expand Down
Loading

0 comments on commit 55b8e03

Please sign in to comment.