-
-
Save jirolabo/f4f2ee7f96cf9351444d55d0d8629314 to your computer and use it in GitHub Desktop.
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; | |
} | |
} | |
} |
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)
+1
Nice simple example. Works in test project too.
+1