Unfortunately, the use of the HttpClientFactory
is tightly integrated with the DI framework. Fortunately, creating a new IHttpClientFactory
without making use of the full DI infrastructure can be done in a few lines:
IHttpClientFactory factory = new ServiceCollection()
.AddHttpClient()
.BuildServiceProvider()
.GetRequiredService<IHttpClientFactory>();
With the code above you create new new service provider (which is the MS.DI Container) that just contains the registrations for the HTTP client package, which includes a registration for IHttpClientFactory
, and the IHttpClientFactory
is directly pulled from the container. The factory is stored in a variable, while the container itself is no longer used.
A full working Console application would like like this:
// This requires the 'Microsoft.Extensions.Http` package to be installed
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;
internal class Program
{
static async Task Main(string[] args)
{
IHttpClientFactory factory = new ServiceCollection()
.AddHttpClient()
.BuildServiceProvider()
.GetRequiredService<IHttpClientFactory>();
HttpClient client = factory.CreateClient();
string html = await client.GetStringAsync(
"https://blogs.cuttingedge.it/steven/p/commands");
Console.WriteLine(html);
Console.ReadLine();
}
}
Best is to cache the IHttpClientFactory
for the lifetime of your application and not recreate it on the fly.