Using HTTPClientFactory in .NET Core Console Application
In today’s post, we will see how to use HTTPClientFactory in .NET Core Console application.
In our last article, we understood the HTTPClient and HTTPClientFactory and also learned best practices to use HTTPClientFactory to create an HTTPClient object which addresses the known issues of HTTPClient request in the traditional way in .NET Core like Resource Exhaustion or Stale DNS problems.
Today in this article, we will cover below aspects,
In our previous article, we already also looked at approaches to create HTTPClient requests in ASP.NET Core API.
Let’s look at the step by step to understand and create a Typed HTTPClient approach where we shall be creating typed HTTPClient using the IHTTPClientFactory interface.
Create a .NET Core Console application
Add below Nuget packages,
PM> Install-Package Microsoft.Extensions.Hosting -Version 3.1.1
PM> Install-Package Microsoft.Extensions.Http -Version 3.1.1
We shall be doing DI(Dependency Injection) in Console application using the generic HostBuilder technique which we learned in our last article.
For References: Dependency Injection in Console application using the Generic HostBuilder
Register HttpClientFactory in DI Container
Register HttpClientFactory in IoC Container using generic HostBuilder as below,
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHttpClient();
services.AddTransient<MyApplication>();
}).UseConsoleLifetime();
Here is the complete code,
class Program
{
static async Task<int> Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHttpClient();
services.AddTransient<MyApplication>();
}).UseConsoleLifetime();
var host = builder.Build();
using (var serviceScope = host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
try
{
var myService = services.GetRequiredService<MyApplication>();
var result = await myService.Run();
Console.WriteLine(result);
}
catch (Exception ex)
{
Console.WriteLine("Error Occured");
}
}
return 0;
}
}
HTTPClient via Constructor DI
Once IHTTPClientFactory is registered, it can be injected from the Constructor of any class.
HTTPClientFactory will be available to use in every class/module in your console application as required. Lifetime management of injected HTTPClient instances will be done through the Service container itself.
This instance can be used for invoking the required operations as shown below,
Below is the complete sample implementation,
public class MyApplication
{
private readonly ILogger _logger;
private readonly IBusinessLayer _business;
private IHttpClientFactory _httpFactory { get; set; }
public MyApplication(ILogger<MyApplication> logger, IBusinessLayer business,
IHttpClientFactory httpFactory)
{
_logger = logger;
_business = business;
_httpFactory = httpFactory;
}
public async Task<string> Run()
{
_logger.LogInformation("Application {applicationEvent} at {dateTime}", "Started", DateTime.UtcNow);
var request = new HttpRequestMessage(HttpMethod.Get,
"https://TheCodeBuzz.com");
var client = _httpFactory.CreateClient();
var response = await client.SendAsync(request);
_business.PerformBusiness();
_logger.LogInformation("Application {applicationEvent} at {dateTime}", "Ended", DateTime.UtcNow);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
return $"StatusCode: {response.StatusCode}";
}
}
}
Additionally, this technique lets you control and configure HTTPClient’s request with a custom configuration of Policy, Security, or delegates as required.
Using CreateDefault Builder as Generic HostBuilder
One can also create Generic HostBuilder using CreateDefaultBuilder. This way your application can get access to application Configuration like apsettings.json or apsettings.{env} .json easily.
var builder = Host.CreateDefaultBuilder().Build();
Using Named HTTPClient
You can use the named HTTPClient if needed as discussed in the below article for ASP.NET Core. but the same concept can be used for Console Applications.
Named HTTPClient using IHttpClientFactory in ASP.NET Core
Using Typed HTTPClient
This is one of the most preferred and easy techniques to create type HTTP Client objects
Typed HTTPClient using HttpClientFactory in ASP.NET Core
That’s all! Hope this article was helpful. Please sounds off your comments below.
Summary
In this article, we looked at how to use HTTPClientFactory in the .NET Core Console application for creating the HTTPClient request object. One can use Named HTTPClient or Typed HTTPCLient techniques to create HTTP request objects as needed.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.