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.

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

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

public static void Main(string[] args)
{
    IWebHost webHost = CreateWebHostBuilder(args).Build();
    CallSomeRemoteService(webHost.Services);
    webHost.Run();
}

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

private static void CallSomeRemoteService(IServiceProvider serviceProvider)
{
    var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
    var httpClient = httpClientFactory.CreateClient("OpenBreweryDb");
    var response = httpClient.GetAsync("?by_state=Massachusetts&by_name=night").Result;
    if (response.IsSuccessStatusCode)
    {
        var breweries = response.Content.ReadAsAsync<List<Brewery>>().Result;
    }
}

That’s it, easy when you know how.

Full source code here.

4 thoughts on “How to use HttpClientFactory Inside Program.cs

  1. Hi,
    I’m trying to use this using NInject but I’m concerned that the documentation for “HttpClientFactory.CreateClient(string)” method states that it “guarantees creating a new instance with every call”, however I thought that the whole point is that your application only has once static HttpClient instance. Am I missing something?
    Thanks
    Chris

    • Hi Chris,
      The client factory does indeed create a new HttpClient instance every time you call it and you should consider these transient and short-lived. Under the hood, the factory manages HttpMessageHandlers which are the piece which does the actual HTTP work. HttpClient is basically a wrapper around a chain of handlers.

      HttpClientFactory manages the lifetime of the handler chains. By default, they live for 2 minutes. Each time a new HttpClient is created, a handler chain is provided to its constructor. If there are existing handler chains in the “cache” then they will be used, which ensures connection re-use occurs. If all handler chains have since expired, a new chain is created, used for the HttpClient and then stored for 2 minutes for re-use.

      I hope that makes things a little clearer.

      I also have some blog posts on this subject, starting at https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore.

      Cheers,
      Steve

Leave a Reply

Your email address will not be published. Required fields are marked *