With the
IHttpClientFactory
, you can either have a standard
HttpClient
keyed by name, or a typed client keyed by type. There is no support for registering different versions of the same typed client.
How about something like this?
public interface ITypedClient
{
Task<T> GetAsync<T>(string url);
}
public class TypedClient : ITypedClient
{
private readonly HttpClient _client;
public TypedClient(HttpClient client, string uuid)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
Uuid = uuid;
}
public string Uuid { get; }
public async Task<T> GetAsync<T>(string url)
{
...
}
}
public interface ITypedClientFactory
{
ITypedClient CreateClient(string uuid);
}
public class TypedClientFactory
{
private readonly IHttpClientFactory _clientFactory;
public TypedClientFactory(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory));
}
public ITypedClient CreateClient(string uuid)
{
var client = _clientFactory.CreateClient(uuid);
return new TypedClient(client, uuid);
}
}
public static class HttpClientStartup
{
public static void ConfigureHttpClient(IServiceCollection services, IAppSettings configuration)
{
services.AddSingleton<ITypedClientFactory, TypedClientFactory>();
foreach (ClientConfigurations clientConfiguration in configuration.ClientConfigurations)
{
string uuid = clientConfiguration.ConfigurationId.ToString();
services.AddHttpClient(uuid, client =>
{
client.BaseAddress = new Uri(clientConfiguration.BaseAddress);
});
}
}
}
var serviceCollection = new ServiceCollection();
HttpClientStartup.ConfigureHttpClient(serviceCollection, AppSettings.ApplicationConfiguration);
var provider = serviceCollection.BuildServiceProvider();
var factory = provider.GetRequiredService<ITypedClientFactory>();
var typedService1 = factory.CreateClient("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4");
var resultList1 = await typedService1.GetAsync<List<Movie>>("api/movies");
var typedService2 = factory.CreateClient("9472D0C4-8252-43E2-B09B-BAB3E874F8A5");
var movieList2 = await typedService2.GetAsync<List<Movie>>("api/books");