I am having issue when adding a custom client with Refit. I dont want default httpClient. The reason to do is that I dont want my consumers to change httpclient configuration when they are consuming my refit implemented Client. Separation of concerns I guess.
I have a class CustomHttpClient which is inherited from httpClient.
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>();
CustomHttpClient.cs
public class CustomHttpClient : HttpClient
{
public CustomHttpClient(HttpMessageHandler handler) : base(handler)
{
}
public CustomHttpClient()
{
}
}
I am getting exception:
System.InvalidOperationException: 'ValueFactory attempted to access the Value property of this instance.'
AddTypedClient adds the client as Transient but I want it as Singleton. I am not sure how to tell Refit to use my CustomHttpClient & CustomHttpClientHandler which should be singleton?
Update: I tried below code and its giving new exception.
serviceCollection.AddSingleton<CustomHttpClient>();
serviceCollection.AddSingleton<CustomHttpClientHandler>();
serviceCollection.AddHttpClient<CustomHttpClient>(c => c.BaseAddress = new Uri("http://dummy.com"));
serviceCollection.AddRefitClient<IMyAPi>().AddHttpMessageHandler<CustomHttpClientHandler>();
System.InvalidOperationException: 'A suitable constructor for type 'BBC.Studios.Rightsline.Client.RightslineHttpClient' could not be located. Ensure the type is concrete and services are registered for all parameters of a public constructor.'