-
Notifications
You must be signed in to change notification settings - Fork 849
Description
Description
Using AddStandardResilienceHandler() does something with the service collection, causing Application Insights' TelemtryClient to go missing from the DI container.
I'm pretty sure (or I hope that) this bug is not related to Application Insights; most likely it has something to do with the way this package changes the ServiceCollection. However, I will demonstrate it using Application Insights because that's how I bumped into this issue.
Reproduction Steps
- Create a Worker Service (.net 8)
- Add latest
Microsoft.ApplicationInsights.WorkerService - Add latest
Microsoft.Extensions.Http.Resilience
Write the following in Program.cs:
using Microsoft.ApplicationInsights;
using Microsoft.Extensions.Http.Resilience;
var builder = Host.CreateApplicationBuilder(args);
// Turn these 2 around to make it work!
builder.Services.AddHttpClient("TEST").AddStandardResilienceHandler();
builder.Services.AddApplicationInsightsTelemetryWorkerService(x =>
x.ConnectionString = "This does not get triggered when set up after the resilience handler");
var host = builder.Build();
// This will throw an exception about TelemetryClient missing in the DI contaner
// To fix this, turn the 2 lines around in the builder.Services code.
_ = host.Services.GetRequiredService<TelemetryClient>();
host.Run();Expected behavior
I would expect that IServiceCollection does NOT require the caller to configure it in a specific order. This is considered a bad practice; the http pipeline in ASP.NET Core is ordered, for example ,but the DI is not.
Actual behavior
Using AddStandardResilienceHandler() modifies the service collection somehow, causing some services to become unresolvable.
Regression?
No response
Known Workarounds
Configure Resilience last in your service collection
Configuration
.NET 8
Windows 11
Other information
The docs mention the following:
Creates a xref:Microsoft.Extensions.DependencyInjection.ServiceCollection instance.
Which changed my mind on guessing this was a resilience <-> app insights issue, and more likely related to how this resilience package modifies the service collection in an illegal/bad practice kind of way.
https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection
Service registration is generally order-independent except when registering multiple implementations of the same type.