使用 Refit 添加自定义客户端时遇到问题。我不想要默认的 httpClient。这样做的原因是我不希望我的消费者在使用我的改装实施客户端时更改 httpclient 配置。我猜是关注点分离。
我有一个继承自 httpClient 的类 CustomHttpClient。
var client = new CustomHttpClient();
serviceCollection.AddRefitClient<IMyAPi>().AddTypedClient(sp => client).ConfigureHttpClient((serviceProvider, httpClient) =>
{
var options = serviceProvider.GetRequiredService<IOptions<CustomClientOptions>>().Value;
httpClient.BaseAddress =
new Uri(
$"{options.ApiProtocol}://{options.ApiHost}/{options.ApiVersion}");
}).AddHttpMessageHandler<CustomHttpClientHandler>();
自定义HttpClient.cs
public class CustomHttpClient : HttpClient
{
public CustomHttpClient(HttpMessageHandler handler) : base(handler)
{
}
public CustomHttpClient()
{
}
}
我得到了例外:
System.InvalidOperationException: 'ValueFactory 试图访问此实例的 Value 属性。'
AddTypedClient 将客户端添加为 Transient,但我希望它为 Singleton。我不确定如何告诉 Refit 使用我的 CustomHttpClient 和 CustomHttpClientHandler 应该是单例的?
更新: 我尝试了下面的代码并给出了新的异常。
serviceCollection.AddSingleton<CustomHttpClient>();
serviceCollection.AddSingleton<CustomHttpClientHandler>();
serviceCollection.AddHttpClient<CustomHttpClient>(c => c.BaseAddress = new Uri("http://dummy.com"));
serviceCollection.AddRefitClient<IMyAPi>().AddHttpMessageHandler<CustomHttpClientHandler>();
System.InvalidOperationException:'找不到适合类型'BBC.Studios.Rightsline.Client.RightslineHttpClient'的构造函数。确保类型是具体的,并且为公共构造函数的所有参数注册了服务。