C# 使用Refit添加自定义类型客户端
我在使用Refit添加自定义客户端时遇到问题。我不想要默认的httpClient。这样做的原因是,我不希望我的客户在使用我的重新安装实现的客户机时更改httpclient配置。我猜是分离关注点 我有一个从httpClient继承的CustomHttpClient类C# 使用Refit添加自定义类型客户端,c#,asp.net-core,asp.net-core-mvc,httpclient,refit,C#,Asp.net Core,Asp.net Core Mvc,Httpclient,Refit,我在使用Refit添加自定义客户端时遇到问题。我不想要默认的httpClient。这样做的原因是,我不希望我的客户在使用我的重新安装实现的客户机时更改httpclient配置。我猜是分离关注点 我有一个从httpClient继承的CustomHttpClient类 var client = new CustomHttpClient(); serviceCollection.AddRefitClient<IMyAPi>().AddTypedClient(sp =
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>();
我得到一个例外:
System.InvalidOperationException:“ValueFactory试图访问
此实例的Value属性。'
AddTypedClient将客户端添加为瞬态,但我希望它作为单例。我不知道如何告诉Refit使用我的CustomHttpClient和CustomHttpClientHandler,这应该是singleton
更新:
我尝试了下面的代码,它给出了新的异常
serviceCollection.AddSingleton<CustomHttpClient>();
serviceCollection.AddSingleton<CustomHttpClientHandler>();
serviceCollection.AddHttpClient<CustomHttpClient>(c => c.BaseAddress = new Uri("http://dummy.com"));
serviceCollection.AddRefitClient<IMyAPi>().AddHttpMessageHandler<CustomHttpClientHandler>();
serviceCollection.AddSingleton();
serviceCollection.AddSingleton();
serviceCollection.AddHttpClient(c=>c.BaseAddress=新Uri(“http://dummy.com"));
serviceCollection.AddRefitClient().AddHttpMessageHandler();
System.InvalidOperationException:'类型的合适构造函数
“BBC.Studios.Rightsline.Client.RightslineHttpClient”无法删除
位于。确保类型是具体的,并且服务已注册
公共构造函数的所有参数。”
FWIW,我想你可能会以一种非常困难的方式来处理这件事。我建议您使用.NET Core中的
IHttpClientFactory
机制,而不是创建HttpClient
的子类。看见也许您可以使用“类型化客户端”样式,但这并不意味着继承HttpClient
。
serviceCollection.AddSingleton<CustomHttpClient>();
serviceCollection.AddSingleton<CustomHttpClientHandler>();
serviceCollection.AddHttpClient<CustomHttpClient>(c => c.BaseAddress = new Uri("http://dummy.com"));
serviceCollection.AddRefitClient<IMyAPi>().AddHttpMessageHandler<CustomHttpClientHandler>();