Passing IHttpClientFactory to .NET Standard class library
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"));
});
Nowadays there is a NuGet package Microsoft.Extensions.Http
offering the IHttpClientFactory to .NET Standard 2.0