Basic of IHttpClientFactory in .NET Core

There are numerous scenarios in which a backend program (a C# console application) or API needs to communicate with another API. In these situations, it’s critical to comprehend how we establish connections to other servers or APIs in order to retrieve data.

Performance problems and a decline in performance will result from improper use of HTTP connections.

I attempted to clarify the problem with HTTP clients in my previous essay.

Opening the connection with the C# code requires caution.

Performance problems will arise if the http connection is opened and closed for every request, as the following article explains.

There are three main symptoms of connection pool starvation.

  1. Timeouts in the form of TaskCanceledException
  2. Latency spikes under load
  3. Low throughput
IHttpClientFactory in .NET Core

When we make an HTTP connection using IHttpClientFactory, we use the concept of connection pooling.

This means each and every time when we need an HTTP client object, we will get an already-created object from the pool and use it.

The cost of creating httpclient will not be there as we are taking the HTTP client object from the pool itself.

The IHttpClientFactory serves as a factory abstraction that can create HttpClient instances with custom configurations.

Understanding above diagram

  1. IHttptpClientFactory Injected to Clientservice
  2. Inside the service, when we need an HTTP client object, we will get it from the pool.
  3. IHttpClientFactory assigns an HttpMessageHandler from a pool to the HttpClient.
  4. Each time you get an HttpClient object from the IHttpClientFactory, a new instance is returned. But each HttpClient uses an HttpMessageHandler that’s pooled and reused by the IHttpClientFactory to reduce resource consumption, as long as the HttpMessageHandler’s lifetime hasn’t expired.
  5. We can configure the lifetime of HTTP client objects and also.

Benefits of IHttptpClientFactory

  1. Resource Management: We can reuse http objects from the pool, which helps in performance improvement
  2. Configuration and Policies: Using a Named client, we can configure multiple HTTP client objects with different configurations of the named client, which we will discuss later in this article.
  3. Integration with Polly: Integration with other third-party libraries to make API resilient

We can use Polly to apply circuit breaker patterns, etc.

Lifetime Management

We can manage the lifetime for httpclient objects.

The HttpMessageHandler objects in the pool have a lifetime, which is the length of time that an HttpMessageHandler instance in the pool can be reused. The default value is two minutes, but it can be overridden per Typed Client. To override it, call SetHandlerLifetime() on the IHttpClientBuilder that’s returned when creating the client, as shown in the following code.

builder.Services.AddHttpClient<productService>()
    .SetHandlerLifetime(TimeSpan.FromMinutes(5));

There are several ways IHttpClientFactory can be used in an app.

  • Basic usage
  • Named clients
  • Typed clients

Basic Usage

  1. We need to inject IHttpClientFactory via DI.
    builder.Services.AddHttpClient();

We need to create a client from IHttpClientFactory. We need to use the code below in the controller.

using HttpClient client = _iHttpClientFactory.CreateClient();

var response = await client.GetAsync("http://google.com");
Here, We will get an object from the object pool.

Named client

We can use named clients when

In the application, we may need multiple HTTP client objects with different pre-setup configurations.

Example: In an e-commerce application, we need to talk to customer API and order API. Then, we may need to send different headers in both cases, and we can achieve this using a named client.

Program.cs

Controller

Here, we have multiple named clients like order service and customer service.

We can configure settings at startup.cs and can use them in various parts of the application as per the requirement.

Typed client

This Allows you to encapsulate HTTP client configuration and logic in a strongly typed class.

We can directly use the HTTP client in the constructor.

This can be particularly useful for consuming third-party APIs, microservices, or any HTTP-based service in a structured and maintainable way.

We can create custom classes like the ones below.


Service Code

Best and Most Recommended ASP.NET Core 8.0.7 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 9.0 web ranking. HostForLIFEASP.NET is highly recommended. In Europe, HostForLIFEASP.NET is the most popular option for first-time web hosts searching for an affordable plan.

Their standard price begins at only €3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFEASP.NET guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFEASP.NET also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.