Typed DI Helper
Generate strongly-typed DI configurations for HttpClient and SignalR
HttpClient Configuration
Why use strongly-typed DI?
Using AddHttpClient<TInterface, TImplementation> ensures your services receive a configured HttpClient automatically. It handles base URLs, default headers, and even resilience patterns in a centralized way.
C# Generated Code
// 1. Define the Client Interface
public interface IMyApiService
{
Task<string> GetDataAsync();
}
// 2. Implement the Client
public class MyApiService : IMyApiService
{
private readonly HttpClient _httpClient;
public MyApiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetDataAsync()
{
return await _httpClient.GetStringAsync("endpoint");
}
}
// 3. Register in Program.cs (DI)
builder.Services.AddHttpClient<IMyApiService, MyApiService>(client =>
{
client.BaseAddress = new Uri("https://api.example.com");
client.Timeout = TimeSpan.FromSeconds(30);
});
// Add standard resilience (Retry, Circuit Breaker, etc.)
// See: https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience
// Requires Microsoft.Extensions.Http.Resilience
builder.Services.AddHttpClient<IMyApiService, MyApiService>()
.AddStandardResilienceHandler();