Skip to content

Instantly share code, notes, and snippets.

@jirolabo
Created March 27, 2019 12:58
Show Gist options
  • Save jirolabo/f4f2ee7f96cf9351444d55d0d8629314 to your computer and use it in GitHub Desktop.
Save jirolabo/f4f2ee7f96cf9351444d55d0d8629314 to your computer and use it in GitHub Desktop.
HttpClientFactory for console application
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
namespace ConsoleApp1
{
// Install-Package Microsoft.Extensions.DependencyInjection
// Install-Package Microsoft.Extensions.Http
class HttpClientCoreSapmle
{
internal void Execute()
{
var httpClient = new ServiceCollection()
.AddHttpClient()
.BuildServiceProvider()
.GetService<IHttpClientFactory>()
.CreateClient();
var html = httpClient.GetStringAsync("https://twitter.com/ko_ro_chin").Result;
}
}
}
@JustinGrote
Copy link

JustinGrote commented Apr 13, 2022

I think what it really shows is you can leave a lot of the DI injection stuff like configuration and logging out if all you care about is getting a central client, however this example is misleading in that your Execute function shouldn't be building a clientfactory each time. Instead you should make the ClientFactory once (ideally as a static class singleton), and then call createClient() where necessary from that, so that all instances share the same HttpClientHandler pool.

Why not just reuse the same HttpClient from the factory? Well HttpClient has some really nice convenience methods like baseurl or defaultrequestheaders that make having multiple httpclients nice, and the factory pattern makes it so they share the real heavyweight component, the clienthandler, the httpclient piece itself is fairly lightweight. This lets you make things like named clients for different websites and typed clients and let your app fetch the appropriate client as needed while still sharing the same clienthandler pool and remaining efficient (and avoiding socket exhaustion)

@robertlyson
Copy link

+1

@vfsdan
Copy link

vfsdan commented Jun 5, 2024

Nice simple example. Works in test project too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment