How to use HttpClientFactory Inside Program.cs

Full source code here.

Over the past week I have written a few articles about HttpClientFactory and dependency injection in .NET Core 2.1. There is one scenario I didn’t deal with - calling a HttpClient from inside the Main method in Program.cs. If you have read my previous post you will probably know how do it, but in case you landed on this post from a search here is how to do it.

In Startup.cs, add the HttpClientFactory to the service collection.

1public void ConfigureServices(IServiceCollection services)
2{
3    services.AddHttpClient("OpenBreweryDb", client =>
4    {
5        client.BaseAddress = new Uri("https://api.openbrewerydb.org/breweries/");
6        client.DefaultRequestHeaders.Add("Accept", "application/json");
7    });
8    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
9}

In Progam.cs I split the building the webHost from running it so I can get at the service collection.

1public static void Main(string[] args)
2{
3    IWebHost webHost = CreateWebHostBuilder(args).Build();
4    CallSomeRemoteService(webHost.Services);
5    webHost.Run();
6}

Then I grab a HttpClientFactory from the service collection and a HttpClient from inside the HttpClientFactory.

 1private static void CallSomeRemoteService(IServiceProvider serviceProvider)
 2{
 3    var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
 4    var httpClient = httpClientFactory.CreateClient("OpenBreweryDb");
 5    var response = httpClient.GetAsync("?by_state=Massachusetts&by_name=night").Result;
 6    if (response.IsSuccessStatusCode)
 7    {
 8        var breweries = response.Content.ReadAsAsync<List<Brewery>>().Result;
 9    }
10}

That’s it, easy when you know how.

Full source code here.

comments powered by Disqus

Related