Passing IHttpClientFactory to .NET Standard class library

Sam picture Sam · Apr 25, 2018 · Viewed 8.6k times · Source

There's a really cool IHttpClientFactory feature in the new ASP.NET Core 2.1 https://www.hanselman.com/blog/HttpClientFactoryForTypedHttpClientInstancesInASPNETCore21.aspx

I'm trying to use this feature in my ASP.NET Core 2.1 Preview-2 app but I need to use the HttpClient in my class libraries which are in .NET Standard 2.0

Once I perform AddHttpClient in ConfigureServices() in Startup.cs, how do I pass this HttpClientFactory or a specific named HttpClient to an API client I created in my .NET Standard 2.0 class library? This client pretty much handles all the API calls I make to a third party.

Basically, I'm just trying to get the specific named HttpClient into my thirdPartyApiClient.

Here's my code in ConfigureServices():

public void ConfigureServices(IServiceCollection services)
{
    // Create HttpClient's
    services.AddHttpClient("Api123Client", client =>
    {
         client.BaseAddress = new Uri("https://api123.com/");
         client.DefaultRequestHeaders.Add("Accept", "application/json");
    });
    services.AddHttpClient("Api4567Client", client =>
    {
         client.BaseAddress = new Uri("https://api4567.com/");
         client.DefaultRequestHeaders.Add("Accept", "application/json");
    });
}

Answer

MichelZ picture MichelZ · May 7, 2020

Nowadays there is a NuGet package Microsoft.Extensions.Http offering the IHttpClientFactory to .NET Standard 2.0