Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Refit添加自定义类型客户端_C#_Asp.net Core_Asp.net Core Mvc_Httpclient_Refit - Fatal编程技术网

C# 使用Refit添加自定义类型客户端

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 =

我在使用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>();
我得到一个例外:

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>();