Per https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory#extending-the-convenience-addtransienthttperrorpolicy-definition I can see policies are added with a name.
var httpClientOptions = HttpPolicyExtensions
.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
.WaitAndRetryAsync(6,
retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
services.AddHttpClient(/*have to add a name*/)
.AddPolicyHandler(httpClientOptions);
I am using Simple Injector in parallel to the .net dependency injection, and I inject the http client factory into my consuming classes as below:
public PolygonIoApiFetcher(IHttpClientFactory clientFactory)
{
this.client = clientFactory.CreateClient(/* what to use here */);
}
My issue is that I have a number of functions written in other libraries that won't necessarily have the client factory policy name shared between libaries.
Furthermore, to keep things simple I would probably want a single poly retry policy for all my HttpClient
created by the factory - is there any way for IHttpClientFactory
to return a default HttpClient
with the default poly policy applied?
I do not want to use a typed registration either per https://github.com/simpleinjector/SimpleInjector/issues/654, and I need to control the lifetime of the object via the IHttpClientFactory
injected as opposed to the HttpClient
being injected into the consuming class.
In summary, the wiring/injection at startup should determine the policy injected and easily rewired/changed, and not by the consuming class.
I have provided what I have done so far, but pointers appreciated if this is, as i suspect, an already solved problem.
Idea below - create a wrapper class
The parameterless HttpClient CreateClient(this IHttpClientFactory factory)
extension method from System.Net.Http
cannot be overridden, so I thought to use the wrapper class and manually select the policy during injection:
public interface IPollyHttpClientFactory
{
HttpClient CreateClient();
}
public class PollyHttpClientFactoryWrapper
{
private readonly string policyName;
private readonly Container container;
public PollyHttpClientFactoryWrapper(
string policyName, Container container)
{
this.policyName = policyName ?? throw new ArgumentNullException();
this.container = container ?? throw new ArgumentNullException();
}
public HttpClient CreateClient()
{
return this.container
.GetInstance<IHttpClientFactory>()
.CreateClient(this.policyName);
}
}
And use during registration:
Container.RegisterSingleton<IHistoricalAggregates>(
() => new PolygonIoApiFetcher(
new PollyHttpClientFactoryWrapper("RetryPolicy", Container),
Container.GetInstance<ApiKeys>().PolygonIoApiKey));
The only "issue" is my classes would need to use the IPollyHttpClientFactory
interface, but I can live with that.