I've been using RateLimiter (github) successfully with my project for a while now. I've recently discovered dependency injection and am attempting to migrate my code as-is to use this but I'm stuck on RateLimiter.
Normal usage from the docs is
var handler = TimeLimiter
.GetFromMaxCountByInterval(25, TimeSpan.FromMinutes(1))
.AsDelegatingHandler();
var Client = new HttpClient(handler)
However if I try to replicate that during dependency injection
public override void Configure(IFunctionsHostBuilder builder)
{
builder.Services.AddHttpClient<IMyApiClient, MyApiClient>(client => client.BaseAddress = new Uri("https://api.myapi.com/"))
.AddPolicyHandler(GetRetryPolicy())
.AddHttpMessageHandler(() => TimeLimiter.GetFromMaxCountByInterval(25, TimeSpan.FromMinutes(1)).AsDelegatingHandler());
}
I receive the error:
[2021-05-17T21:58:00.116Z] Microsoft.Extensions.Http: The 'InnerHandler' property must be null. 'DelegatingHandler' instances provided to 'HttpMessageHandlerBuilder' must not be reused or cached.
[2021-05-17T21:58:00.117Z] Handler: 'ComposableAsync.DispatcherDelegatingHandler'.
[2021-05-17T21:58:00.122Z] An unhandled host error has occurred.
My class client structure (mostly for the sake of unit testing) looks like this:
using System.Net.Http;
using System.Threading.Tasks;
public class MyApiClient : HumbleHttpClient, IMyApiClient
{
public MyApiClient(HttpClient client)
: base(client)
{
}
}
public class HumbleHttpClient : IHttpClient
{
public HumbleHttpClient(HttpClient httpClient)
{
this.Client = httpClient;
}
public HttpClient Client { get; }
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return this.Client.GetAsync(requestUri);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return this.Client.PostAsync(requestUri, content);
}
}
public interface IHttpClient
{
Task<HttpResponseMessage> GetAsync(string requestUri);
Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content);
HttpClient Client { get; }
}
These are the docs I've been trying to follow: https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests
