Introduction
I am developing SDK (that is just a wrapper for an REST API). This SDK is internally using the HttpClient to make requests for the API. The SDK targets .NET Standard 2.1. Here is simplified code.
public class SomeSdk
{
private readonly HttpClient _httpClient;
public SomeSdk(<some-settings>)
{
_httpClient = new HttpClient(<some-settings>);
}
public async Task<string> GetSomethingFromApiAsync()
{
return await _httpClient.GetStringAsync(...);
}
}
Issue
The SDK is being used by other developers in ASP.NET Core projects. I am aware of the troubles with HttpClient and I know that MS DOCS recommand to inject HttpClientFactory to avoid SocketException and to reflect DNS changes.
First solution that comes to mind is to let the user pass the HttpClient (that is from HttpClientFactory) in the SDK constructor or other methods. Like this.
public async Task<string> GetSomethingFromApiAsync(HttpClient clientFromFactory)
{
return await clientFromFactory.GetStringAsync(...);
}
However there is problem that the SDK configures the HttpClient before it uses it (Proxy, Timeout, etc.) Therefore it's initialization should be left in the SDK constructor.
Question
My current solution is to inject SDK as singleton in the ASP.NET Core projects and accept the DNS reflection issues. I would still like to ask if there is anyone who would recommand me a better approach for this problem.
Thank you very much, Adam.