feat: Refactor RaceUploadCommunicationClient and RaceUploadTabView to improve HttpClient management and resource disposal
This commit is contained in:
parent
b29cc95a1e
commit
bdf503c627
3 changed files with 145 additions and 81 deletions
|
|
@ -2,6 +2,8 @@ using System.Net;
|
|||
using Catalog.Communication.Abstractions;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Catalog.Communication.DependencyInjection;
|
||||
|
|
@ -25,22 +27,30 @@ public static class CatalogCommunicationServiceCollectionExtensions
|
|||
|
||||
services.TryAddSingleton<CookieContainer>();
|
||||
|
||||
services
|
||||
.AddHttpClient<IRaceUploadCommunicationClient, RaceUploadCommunicationClient>((sp, client) =>
|
||||
// Create the HttpClient only when the communication client is requested.
|
||||
// This avoids constructing the DefaultHttpClientFactory (and its background cleanup timer)
|
||||
// if the race-upload feature is never used.
|
||||
services.AddTransient<IRaceUploadCommunicationClient>(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<CatalogCommunicationOptions>>().Value;
|
||||
var logger = sp.GetService<ILogger<RaceUploadCommunicationClient>>() ?? NullLogger<RaceUploadCommunicationClient>.Instance;
|
||||
var cookieContainer = sp.GetRequiredService<CookieContainer>();
|
||||
|
||||
var handler = new HttpClientHandler
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<CatalogCommunicationOptions>>().Value;
|
||||
client.BaseAddress = options.BaseUri;
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(sp =>
|
||||
UseCookies = true,
|
||||
CookieContainer = cookieContainer,
|
||||
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
|
||||
};
|
||||
|
||||
var httpClient = new HttpClient(handler, disposeHandler: true)
|
||||
{
|
||||
var cookieContainer = sp.GetRequiredService<CookieContainer>();
|
||||
return new HttpClientHandler
|
||||
{
|
||||
UseCookies = true,
|
||||
CookieContainer = cookieContainer,
|
||||
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
|
||||
};
|
||||
});
|
||||
BaseAddress = options.BaseUri,
|
||||
Timeout = options.RequestTimeout,
|
||||
};
|
||||
|
||||
return new RaceUploadCommunicationClient(httpClient, sp.GetRequiredService<IOptions<CatalogCommunicationOptions>>(), logger);
|
||||
});
|
||||
|
||||
return services;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue