microsoft / ApplicationInsights-Profiler-AspNetCore

Application Insights Profiler sample and documentation
MIT License
66 stars 22 forks source link

The scheduling policy of OneTimeSchedulingPolicy is not registered to an orchestrator. #192

Closed mispencer closed 1 year ago

mispencer commented 1 year ago

I get the following error on startup:

fail: Microsoft.ApplicationInsights.Profiler.Core.Orchestration.OneTimeSchedulingPolicy[0]
      The scheduling policy of OneTimeSchedulingPolicy is not registered to an orchestrator.

I assume this is due to using a custom CI container. Given that, how do I register it with an orchestrator?

This error doesn't appear to block other profiling types from running successfully.

xiaomi7732 commented 1 year ago

Hi @mispencer , Thanks for the report. It is possible for services not to be registered correctly with a custom DI container. Without knowing specifics, it is difficult for us to understand what exactly the cause is. Is it possible for you to provide us with a mini-project that reproduces the issue?

BTW, which version of the package are you using?

mispencer commented 1 year ago

I created a example project that shows this error on dotnet run.

This is using version 2.5.1 of Microsoft.ApplicationInsights.Profiler.AspNetCore.

xiaomi7732 commented 1 year ago

Hi @mispencer, thanks for providing the example code. It is a bug.

Issue: wrong lifetime for OneTimeSchedulingPolicy:

serviceCollection.AddTransient<SchedulingPolicy, OneTimeSchedulingPolicy>(); // It is registered transient
// Compare to other policies all as singleton:
serviceCollection.AddSingleton<SchedulingPolicy, RandomSchedulingPolicy>();
serviceCollection.AddSingleton<SchedulingPolicy, OnDemandSchedulingPolicy>();

Direct cause: Policies are injected, and then enumerated twice in the orchestrator. The first time to register it with the orchestrator; the 2nd time to activate the policy. Upon the 2nd enumerating, OneTimeScheudlingPolicy gets a new instance - thus not registered - and the error message - and it can't be activated.

That behavior is different than when it is used with Microsoft.Extensions.DependencyInjection, where the policies are all captured by the orchestrator, and thus has an effective lifetime of a singleton.

Having a mismatched lifetime for services is not a good practice. I'll prepare a PR to fix the bug and I'll post updates when the fix is released.

Unfortunately, until then, there's no easy workaround - unless there's a way to manipulate the lifetime of OneTimeScheudlingPolicy to singleton somehow using NinjectServiceProviderFactory, or change the behavior to let the service being captured.

xiaomi7732 commented 1 year ago

Please try the newly released 2.5.2-beta1 package: https://www.nuget.org/packages/Microsoft.ApplicationInsights.Profiler.AspNetCore/2.5.2-beta1

mispencer commented 1 year ago

This issue doesn't occur after upgrading to that version.