IHttpClientFactory in ASP.NET Core: a better way to make the HTTP request
IHttpClientFactory is an interface in the System.Net.Http namespace. Which is a factory abstraction for components to create an HttpClient instance with a custom configuration.
Advantages
- It provides a central location for naming and configuring logical
HttpClient
instances. - It provides extensions for Polly-based middleware for HttpClient.
- Avoid common DNS problems by managing HttpClient lifetimes.
Http request without IHttpClientFactory (Wrong way)
There are some drawbacks to creating HttpClient multiple times. Here is a detailed article explaining just that. There are many reasons to avoid following code. First and foremost it reduces maintainability, it creates Socket Exhaustion in multiple HTTP call cases, and it is just a boilerplate code.
Ways to use IHttpClientFactory
- Basic usage (Setup services.AddHttpClient() in Startup.cs, usector DI to load Factory & use factory.CreateClient())
- Named clients
- Typed clients
Here I’m going to explain Named & Type clients with examples…
Named Clients
IHttpClientFactory has CreateClient(String) method and CreateClient(HttpClientFactory) extension method to create HttpClient instance.
Step 1: Setup HttpClient configuration in Startup.ConfigureService
Please do configure base properties in Startup. You can always change the config. at the time of the actual call.
Step 2: Use Dependency Injection for IHttpClientFactory
Implement Dependency Injection at the constructor & use the IHttpClientFactory instance in the controller.
Step 3: CreateClient using named type
Here you create a client using an already configured factory name. Now configure additional properties for HttpCient as per your need & lastly actual HTTP call handle response.
Typed Client
To Create Typed Client We Can create a Separate service that uses DI to create HttpClient and internally handle the creation of IHttpClientFactory.
Step 1: Create Service class
Create Interface and implement it in GithubService class. We have used DI of HttpClient and IHttpClientFactory creation will be internally managed. Make sure to create a private HttpClient field.
Step 2: Call the Service
Step 3: Setup Service DI in Startup.ConfigureService
Same as the Named client we can set up all common headers, and base address in the ConfigureServices method but the major difference between Named and Typed clients is that we use separate service classes to manage HttpClient calls.