I'm exploring best practices for Dependency Injection and loose coupling in .NET, and I have a question regarding my use of HttpClient.
I register a named HttpClient in Program.cs and then inject IHttpClientFactory into my Auth class to create a HttpClient instance. I'm curious if this approach is in line with DI principles or if creating a concrete HttpClient via the factory introduces unwanted tight coupling.
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}");
}
}
}