dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
15.48k stars 4.76k forks source link

Reduce number of exceptions in HttpClientFactory #106399

Open Ilchert opened 3 months ago

Ilchert commented 3 months ago

Description

After updating to .net 8 from .net 7 we faced with many of first chance exceptions in our services with following stack trace.

System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.Http.DefaultHttpClientFactory.<.ctor>b__14_1()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
--- End of stack trace from previous location ---
   at System.Lazy`1.CreateValue()
   at Microsoft.Extensions.Http.DefaultHttpClientFactory.Log.TryGetLogger(Lazy`1 loggerLazy, ILogger& logger)

Reproduction Steps

AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

void CurrentDomain_FirstChanceException(object? sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
{
    Console.WriteLine(e.Exception.ToString()); // this will print ObjectDisposedException
}

var sc = new ServiceCollection();
sc.AddHttpClient("client").SetHandlerLifetime(TimeSpan.FromSeconds(3));
var sp = sc.BuildServiceProvider();

var f = sp.GetRequiredService<IHttpClientFactory>();
using var httpClient = f.CreateClient("client");

sp.Dispose();

await Task.Delay(10000);

Expected behavior

Should not throw unnecessary exceptions.

Actual behavior

Throw ObjectDisposedException.

Regression?

Yes, works fine in .net 7

Known Workarounds

No response

Configuration

.NET 8 SDK 8.0.303

Other information

It is related to this empty catch block and captured by our logging system. https://github.com/dotnet/runtime/blob/ed13b35174ac5b282adf0aaade335276a762159b/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs#L382-L386

dotnet-policy-service[bot] commented 3 months ago

Tagging subscribers to this area: @dotnet/ncl See info in area-owners.md if you want to be subscribed.