I work on a company’s bff project. That’s why we throw so many http calls. The project is coded with .Net5 . I saw that HttpClient was used when making Http calls, and I thought it would be better if I created HttpClient using IHttpClientFactory to make socket usage more efficient in best practices.
A DI was made like this for HttpClients in the startup file
services.AddHttpClient<TClient, TImplementation>(c =>
{
c.BaseAddress = new Uri(settings.Url);
c.Timeout = settings.Timeout;
})
.ConfigurePrimaryHttpMessageHandler(sp => new DefaultHttpClientHandler())
.AddHttpMessageHandler<OutgoingRequestHandler>()
.AddHttpMessageHandler(serviceProvider =>
new TraceLogHandler(serviceProvider.GetRequiredService<ILogger<TraceLogHandler>>(), settings.Logging));
When I hovered the mouse over the AddHttpClient method, I saw the following explanation:
Adds the IHttpClientFactory and related services to the
IServiceCollection and configures a binding between the TClient type
and a named HttpClient. The client name will be set to the type name
of TClient.
I didn’t understand that in this usage, the use of Socket manages my IHttpClientFactory. Or is it used with IHttpClientFactory integrated?
2
Answers
The explanation is fully correct. You can see source code of it in official .NET repo:
Creation and disposing of clients (and, what is more important, underlying handlers) is fully controlled by HttpClientFactory, you should not do it yourself. This is recommended way by Microsoft. More information about using HttpClients in official guidelines.
I think your answer is the IHttpClientFactory will drive the socket as needed when you instantiate it in a classe with DI by the container that is created with this implementation.
The factory method, introduce messages handlers, that will be who will manage request and websockets available to use.