Can I use HttpClientFactory in a .NET.core app which is not ASP.NET Core?

Noel picture Noel · Oct 3, 2018 · Viewed 16.4k times · Source

I have read the popular blog post https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore on using HttpClientFactory

To quote from it

A new HttpClientFactory feature is coming in ASP.NET Core 2.1 which helps to solve some common problems that developers may run into when using HttpClient instances to make external web requests from their applications.

All the examples show wiring it up in startup class of asp.net application e.g.

public void ConfigureServices(IServiceCollection services)
{
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddHttpClient();
} 

My question is can you use outside of ASP.NET core? And if so are there examples

I would have thought lots of non web applications(.net core apps) need to make web calls, so why was this not part of .net core api instead of putting into asp.net core api

Answer

Alex Riabov picture Alex Riabov · Oct 3, 2018

According to the documentation HttpClientFactory is a part of .Net Core 2.1, so you don't need ASP.NET to use it. And there some ways to use are described. The easiest way would be to use Microsoft.Extensions.DependencyInjection with AddHttpClient extension method.

static void Main(string[] args)
{
    var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();

    var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();

    var client = httpClientFactory.CreateClient();
}