Skip to content

Commit 55b8e03

Browse files
committed
Remove AddSingletonIfNotExists and call TryAddSingleton to fix bugs when keyed services are registered.
1 parent e34286b commit 55b8e03

File tree

6 files changed

+133
-193
lines changed

6 files changed

+133
-193
lines changed

NETCORE/src/Shared/Extensions/ApplicationInsightsExtensions.cs

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -280,26 +280,6 @@ internal static void AddTelemetryConfiguration(
280280
}
281281
}
282282

283-
/// <summary>
284-
/// The AddSingleton method will not check if a class has already been added as an ImplementationType.
285-
/// This extension method is to encapsulate those checks.
286-
/// </summary>
287-
/// <remarks>
288-
/// Must check all three properties to avoid duplicates or null ref exceptions.
289-
/// </remarks>
290-
/// <typeparam name="TService">The type of the service to add.</typeparam>
291-
/// <typeparam name="TImplementation">The type of the implementation to use.</typeparam>
292-
/// <param name="services">The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the service to.</param>
293-
internal static void AddSingletonIfNotExists<TService, TImplementation>(this IServiceCollection services)
294-
where TService : class
295-
where TImplementation : class, TService
296-
{
297-
if (!services.Any(o => o.ImplementationFactory == null && typeof(TImplementation).IsAssignableFrom(o.ImplementationType ?? o.ImplementationInstance.GetType())))
298-
{
299-
services.AddSingleton<TService, TImplementation>();
300-
}
301-
}
302-
303283
private static bool TryGetValue(this IConfiguration config, string primaryKey, out string value, string backupKey = null)
304284
{
305285
value = config[primaryKey];
@@ -332,7 +312,7 @@ private static void AddCommonInitializers(IServiceCollection services)
332312
private static void AddCommonTelemetryModules(IServiceCollection services)
333313
{
334314
// Previously users were encouraged to manually add the DiagnosticsTelemetryModule.
335-
services.AddSingletonIfNotExists<ITelemetryModule, DiagnosticsTelemetryModule>();
315+
services.TryAddSingleton<ITelemetryModule, DiagnosticsTelemetryModule>();
336316

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

0 commit comments

Comments
 (0)