15

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");
    });
}
Lukas
  • 1,699
  • 1
  • 16
  • 49
Sam
  • 26,817
  • 58
  • 206
  • 383

2 Answers2

37

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

MichelZ
  • 4,214
  • 5
  • 30
  • 35
20

First, your library class' constructor should take an HttpClient param, so you can inject an HttpClient into it. Then, the easiest method (mentioned in the link article as well for what it's worth) is to simply add a specific HttpClient for that library class:

services.AddHttpClient<MyLibraryClass>(...);

Then, of course, register your library class for injection, if you haven't already:

services.AddScoped<MyLibraryClass>();

Then, when your library class is instantiated to be injected into something, it too will be injected with the HttpClient you specified for it.

Alternatively, you can manually specify an HttpClient instance to inject via:

services.AddScoped(p => {
    var httpClientFactory = p.GetRequiredService<IHttpClientFactory>();
    return new MyLibraryClass(httpClientFactory.Create("Foo"));
});
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 2
    Update: `AddHttpClient` already handles the registration of the service for you in this scenario. You may get an error if you do it in the above approach. Refer: https://github.com/dotnet/extensions/issues/1079 – Isham Mohamed Jun 01 '20 at 04:57