Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Buggy behaviour in AddApplicationInsightsTelemetryWorkerService when a Keyed service has been added previously #2948

Open
victorhubbers opened this issue Jan 17, 2025 · 0 comments
Labels

Comments

@victorhubbers
Copy link

victorhubbers commented Jan 17, 2025

  • Microsoft.ApplicationInsights.WorkerService Version 2.22.0
  • Microsoft.Extensions.DependencyInjection 9.0.1
  • .NET 8
  • Windows, but reproducible within an MSTest project.

Describe the bug

Not all the applicationinsights dependencies are added to DI if there has been a Keyed service registered before calling the AddApplicationInsightsTelemetryWorkerService extension method. This causes many exceptions at runtime when you would expect the services to have been added. I ran into a DI issue stating that the TelemetryClient was not registered but there is more missing that just this client.

To Reproduce

  • Create blank MSTest project and add dependencies listed above.
  • Implement the following test:
using Microsoft.Extensions.DependencyInjection;

namespace TestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var services1 = new ServiceCollection();
            var services2 = new ServiceCollection();

            services1.AddApplicationInsightsTelemetryWorkerService();
            services1.AddKeyedScoped<ICalculator, LoggingCalculator>("key1");

            services2.AddKeyedScoped<ICalculator, QuietCalculator>("key2");
            services2.AddApplicationInsightsTelemetryWorkerService();

            // Fails because services1.Count is 32 and services2.Count is 5
            Assert.Equals(services1.Count, services2.Count);
        }
    }


    public interface ICalculator
    {
        int Sum(int a, int b);
    }

    public class LoggingCalculator : ICalculator
    {
        public int Sum(int a, int b)
        {
            Console.WriteLine($"Sum of {a} and {b} is {a + b}");
            return a + b;
        }
    }

    public class QuietCalculator : ICalculator
    {
        public int Sum(int a, int b)
        {
            return a + b;
        }
    }

}
@victorhubbers victorhubbers changed the title Inconsistent and unexpected behaviour in AddApplicationInsightsTelemetryWorkerService when a Keyed service has been added previously Buggy behaviour in AddApplicationInsightsTelemetryWorkerService when a Keyed service has been added previously Jan 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant