I wrote a WebAPI in .NET Core and used IHttpClientFactory for creating httpClients. I customized it on Startup.cs in ConfigurationServices.
services.AddHttpClient("ITSMServiceClient", m =>
{
m.DefaultRequestHeaders.Accept.Clear();
m.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
}).SetHandlerLifetime(TimeSpan.FromMinutes(10))
.ConfigurePrimaryHttpMessageHandler(() =>
{
var handler = new HttpClientHandler()
{
AllowAutoRedirect = false,
UseCookies = false
};
// Отключаем проверку валидности http-сертификата (если необходимо)
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) => true;
return handler;
});
Then I use it in one dataProvider via DI.
private readonly IHttpClientFactory _clientFactory;
public ExecuteDataProvider(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
I use methods of this provider for all sending requests
public async Task<HttpResponseMessage> PostAsync(HttpRequestMessage request)
{
using (var client = _clientFactory.CreateClient("ITSMServiceClient"))
{
return await client.SendAsync(request);
}
}
And I have a question. Is it normal behavior always get new instance from _clientFactory even if I can reuse instance twice or more in code? All my dataProvider and another entyties describe like SingleInstance in DI.
builder.RegisterType<ExecuteDataProvider>().As<IExecuteDataProvider>().SingleInstance();
Now I use it something like this:
var request = CreatePostRequest(url, parameters, jParameters, checkingToken);
HttpResponseMessage httpResponseMessage = await _executeCoreDataProvider.PostAsync(request);
if (await CheckingForUnauthorizedToken(httpResponseMessage, checkingToken))
{
request = CreatePostRequest(url, parameters, jParameters, checkingToken);
httpResponseMessage = await _executeCoreDataProvider.PostAsync(request);
}
response = await httpResponseMessage.Content.ReadAsStringAsync();
httpResponseMessage.Dispose();
And I worry about twice getting HttpClient. Is it normal or use one instance of client will be more correctly?
I've already read about ClientFactory on Microsoft Docs; this, and also some other sites.