My use case: I'm writing an app that needs to connect to a multitenant API. The base address, headers, and authentication for each request will vary from request to request.

I came across the concept of IHttpClientFactory in .NET Core, and I think I understand the underlying logic. It gives you a new HttpClient every time; HttpClientHandlers (what is doing the work) are created and managed by IHttpClientFactory and potentially can be reused.

My question: is it safe to use IHttpClientFactory (that reuses the HttpClientHandlers between requests) when I have to connect to different tenant's APIs? - thus different endpoints / base address / headers / auth. Can info from one request leak or contaminate the subsequent request?

I will create new HttpMessageRequest objects for each call, and I will have different HttpClients provided by IHttpClientFactory, yes...

PS: From Make HTTP requests using IHttpClientFactory in ASP.NET Core Microsoft discloses CookieContainer's are shared and that if you have cookie handling requirements, stay away from IHttpClientFactory or disable Cookie handling.

1

There are 1 best solutions below

1
Qiang Fu On

It is said when using IClientFactory, you need

Just using httpclient with setting the PooledConnectionLifetime to desired interval is also recommanded. https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use