I have a scenario where I am configuring multiple HttpClient
instances in Startup.cs
which use same HttpClientHandlers
. The only difference between those HttpClients
is the BaseAddress
property and the name of respective HttpClient
instance since I'm using named HttpClients
.
I was wondering if there is a possibility to create either a default HttpClient
where I'd be adding all those handlers and then the named instances would inherit them or if there is some other way how can I centrally add those handlers without having to manually add them for each HttpClient
instance.
private void ConfigureHttpClients(IServiceCollection services)
{
services.AddHttpClient<IService1, Service>(client =>
{
client.BaseAddress = new Uri("http://api.test.com/");
})
.UseErrorHandling()
.UseDefaultHeaders();
services.AddHttpClient<IService2, Service2>(client =>
{
client.BaseAddress = new Uri("http://api.test-test.com/");
})
.UseErrorHandling()
.UseDefaultHeaders();
}
An improvement for the situation could be an extensionmethod like this:
which can then be used as
in Startup.cs
UPDATE
If the Lambda gets mistaken for a
Func<HttpClient, TClient>
you'll get a "Not all code paths return a value".You can fix this like so:
Seems strange, but I haven't found a better solution, yet.