HTTP Requests Using IHttpClientFactory

Introduction 

 
the very first time Microsoft launched the HttpClient in .NET Framework 4.5, it became the most popular way to consume a Web API HTTP request, such as Get, Put, Post, and Delete in your .NET server-side code.
 
However, it has some serious issues, for example, disposing of the object like HttpClient object doesn’t dispose of the socket as soon as it is closed.
There are also too many instances open so that it affecting the performance and private HttpClientor shared HttpClient instance not respecting the DNS Time.
 
When Microsoft released dotnet core 2.1, it introduced HttpClientFactory that solves all these problems.
 
Basically, it provides a single place (central place) for configuration and consumption HTTP Verbs Client in your application IHttpClientFactory offers the following benefits,
  1. Naming and configuring HttpClient instances.
  2. Build an outgoing request middleware to manage cross-cutting concerns around HTTP requests.
  3. Integrates with Polly for transient fault handling.
  4. Avoid common DNS problems by managing HttpClient lifetimes.
There are the following ways to use IHttpClientFactory.
  1. Direct HttpClientFactory
  2. Named Clients
  3. Typed Clients
We will see an example one by one for all 3 types...
 

Direct HttpClientFactory

 
In dotnet core, we have Startup.cs class, and inside this class, we have the ConfigureService method. In this method we use middleware, where we inject some inbuilt/custom pipeline.
 
So for HttpClientFactory we need to register HttpClient like below:
  1. services.AddHttpClient();  
Now the question is how to use this in our API controller.
 
So here is the example of Direct HttpClientFactory use in controller:
  1. public class HttpClientFactoryController: Controller {  
  2.     private readonly IHttpClientFactory _httpClientFactory;  
  3.     public HttpClientFactoryController(IHttpClientFactory httpClientFactory) {  
  4.             _httpClientFactory = httpClientFactory;  
  5.         }  
  6.         [HttpGet]  
  7.     public async Task < ActionResult > Get() {  
  8.         var client = _httpClientFactory.CreateClient();  
  9.         client.BaseAddress = new Uri("http://api.google.com");  
  10.         string result = await client.GetStringAsync("/");  
  11.         return Ok(result);  
  12.     }  

Here in this example we have pass IHttpClientFactory is a dependency injection and directly use _httpClientFactory.CreateClient();
 
This example is better in this situation when we need to make a quick request from a single place in the code
 

Named Clients

 
Just above I have explained how to register the middleware in startup.cs class in configureService method for HttpClient same we can use for Named Clients as well, but this is useful when we need to make multiple requests from multiple locations.
 
We can also do some more configuration while registering, like this:
  1. services.AddHttpClient("g", c =>  
  2. {  
  3.    c.BaseAddress = new Uri("https://api.google.com/");  
  4.    c.DefaultRequestHeaders.Add("Accept""application/json");  
  5. });  
Here in this configuration, we use two parameter names and an Action delegate taking a HttpClient
 
We can use the named client in the API controller in this way:
  1. public class NamedClientsController: Controller {  
  2.     private readonly IHttpClientFactory _httpClientFactory;  
  3.     public NamedClientsController(IHttpClientFactory httpClientFactory) {  
  4.             _httpClientFactory = httpClientFactory;  
  5.         }  
  6.         [HttpGet]  
  7.     public async Task < ActionResult > Get() {  
  8.         var client = _httpClientFactory.CreateClient("g");  
  9.         string result = await client.GetStringAsync("/");  
  10.         return Ok(result);  
  11.     }  

Note
"g" indicates names client that I use in during registration and also call from the API action method
 

Typed Clients

 
A types client provides the same capabilities as named clients but without the need to use strings as keys in configuration. Due to this it also provide IntelliSense and compiler help when consuming clients. It provides a single location to configure and interact with a particular httpclient
 
It works with dependency injection and can be injected where required in the application.
 
A typed client accepts an HttpClient parameter in its constructor,
 
We can see here by an example that I have defined custom class for httpclient:
  1. public class TypedCustomClient {  
  2.     public HttpClient Client {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public TypedCustomClient(HttpClient httpClient) {  
  7.         httpClient.BaseAddress = new Uri("https://api.google.com/");  
  8.         httpClient.DefaultRequestHeaders.Add("Accept""application/json");  
  9.         httpClient.DefaultRequestHeaders.Add("User-Agent""HttpClientFactory-Sample");  
  10.         Client = httpClient;  
  11.     }  

Now we can register this as a typed client using in this way in startup.cs clss under configureService method.
  1. services.AddHttpClient<TypedCustomClient>();  
Now this time we see how we can use it in API controller,
  1. public class TypedClientController: Controller {  
  2.     private readonly TypedCustomClient _typedCustomClient;  
  3.     public TypedClientController(TypedCustomClient typedCustomClient) {  
  4.             _typedCustomClient = typedCustomClient;  
  5.         }  
  6.         [HttpGet]  
  7.     public async Task < ActionResult > Get() {  
  8.         string result = await _typedCustomClient.client.GetStringAsync("/");  
  9.         return Ok(result);  
  10.     }  

Now we have learned all three types to use.
 
But here is one better way to use typeclient using an interface.
 
We will create an interface and encapsulate all the logic here, that also helps in writing UTC as well
 
Here is an example:
  1. public interface ICustomClient  
  2. {  
  3.   Task<string> GetData();  
  4. }  
Now inherit this interface in custom class
  1. public class TypedCustomClient: ICustomClient {  
  2.     public HttpClient Client {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public TypedCustomClient(HttpClient httpClient) {  
  7.         httpClient.BaseAddress = new Uri("https://api.google.com/");  
  8.         httpClient.DefaultRequestHeaders.Add("Accept""application/json");  
  9.         httpClient.DefaultRequestHeaders.Add("User-Agent""HttpClientFactory-Sample");  
  10.         Client = httpClient;  
  11.     }  

Register this in startup class:
  1. services.AddHttpClient<ICustomClient, TypedCustomClient>();  
  1. public class CustomController: Controller {  
  2.     private readonly ICustomClient _iCustomClient;  
  3.     public ValuesController(ICustomClient iCustomClient) {  
  4.             _iCustomClient = iCustomClient;  
  5.         }  
  6.         [HttpGet]  
  7.     public async Task < ActionResult > Get() {  
  8.         string result = await iCustomClient.GetData();  
  9.         return Ok(result);  
  10.     }  

Here we are using the interface for the same, so it would be good to go for repository mock. 
 
Thank you for taking your valuable time to read the full article!


Similar Articles