I want to ensure I'm following best practices for building loosely coupled code using dependency injection, and I'm seeking clarity on whether my approach to creating an HttpClient is appropriate.
I configure the HttpClient in Program.cs and then instantiate it within a property in my Auth class using IHttpClientFactory. Does this approach adhere to dependency injection principles, or does it introduce tight coupling by using a concrete instance of HttpClient?
Program.cs:
builder.Services.AddHttpClient("AuthService", client =>
{
client.BaseAddress = new Uri(builder.Configuration.GetValue<string>("Address")!);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
AllowAutoRedirect = false,
UseCookies = true
});
Auth.cs:
public class Auth(IHttpClientFactory httpClientFactory)
{
...
private HttpClient client = httpClientFactory.CreateClient("Auth");
...
public async Task<Result<Uri>> GetStuff()
{
try
{
using var response = await client.GetAsync("www.example.com");
if (response.StatusCode == HttpStatusCode.OK)
return Result<Uri>.Success(cachedLocation);
}
catch (HttpRequestException ex)
{
return Result<Uri>.Failure($"HTTP request failed: {ex.Message}");
}
}
}