【发布时间】:2021-05-17 22:12:12
【问题描述】:
我已经在我的项目中成功使用RateLimiter (github) 有一段时间了。我最近发现了依赖注入,并试图按原样迁移我的代码以使用它,但我被困在 RateLimiter 上。
文档中的正常用法是
var handler = TimeLimiter
.GetFromMaxCountByInterval(25, TimeSpan.FromMinutes(1))
.AsDelegatingHandler();
var Client = new HttpClient(handler)
但是,如果我尝试在依赖注入期间复制它
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());
}
我收到错误:
[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.
我的类客户端结构(主要是为了单元测试)如下所示:
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; }
}
【问题讨论】:
标签: c# .net-core dependency-injection dotnet-httpclient