microsoft / ApplicationInsights-Kubernetes

Enrich the telemetry data for .NET applications running inside containers that are managed by Kubernetes.
Other
135 stars 57 forks source link

Can't register Enrichers when using KeyedServices #355

Closed tomaszzmuda closed 3 months ago

tomaszzmuda commented 5 months ago

Describe the bug Can't register Enrichers when using KeyedServices when using .NET 8

Package Versions Application Insights Kubernetes Version: 6.1.1 Application Insights SDK Version: 2.22.0

To Reproduce Steps to reproduce the behavior:

  1. Create .NET 8 application with dependency injection and keyed services
  2. Try to invoke AddApplicationInsightsKubernetesEnricher
  3. Get an exception

Expected behavior It is possible to add Kubernetes enrichers when you used keyed services.

Screenshots Stacktrace: image

Additional context

https://github.com/AzureAD/microsoft-identity-web/issues/2604

In AddApplicationInsightsKubernetesEnricher method there is a check if initalizer already exists: KubernetesTelemetryInitializerExists. Implementation of that method checks if any ImplementationType from service collection is of type KubernetesTelemetryInitializer but getting ImplementationType property by design throws exception if it's keyed service.

/// <summary>
/// Gets the <see cref="Type"/> that implements the service.
/// </summary>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
public Type? ImplementationType
{
    get
    {
        if (IsKeyedService)
        {
            ThrowKeyedDescriptor();
        }
        return _implementationType;
    }
}
//
// Summary:
//     Checks if the KubernetesTelemetryInitializer exists in the service collection.
//
//
// Parameters:
//   serviceCollection:
//     The service collection.
private static bool KubernetesTelemetryInitializerExists(IServiceCollection serviceCollection)
{
    return serviceCollection.Any((ServiceDescriptor t) => t.ImplementationType == typeof(KubernetesTelemetryInitializer));
}
xiaomi7732 commented 5 months ago

Beta package is released, please give it a try. https://www.nuget.org/packages/Microsoft.ApplicationInsights.Kubernetes/6.1.2-beta1