Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing IHttpClientFactory to .NET Standard class library

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");
    });
}
like image 680
Sam Avatar asked Apr 25 '18 17:04

Sam


2 Answers

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

like image 171
MichelZ Avatar answered Oct 22 '22 06:10

MichelZ


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"));
});
like image 29
Chris Pratt Avatar answered Oct 22 '22 06:10

Chris Pratt