3

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.'

Kamran Pervaiz
  • 1,861
  • 4
  • 22
  • 42
  • FWIW, I think you might be going about this in a way that will be very difficult. Rather than creating a subclass of `HttpClient`, I recommend that you use the `IHttpClientFactory` mechanisms in .NET Core. See https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2. Perhaps you will be able to use a "Typed Client" style, but that does not imply inheriting `HttpClient`. – Alan McBee Sep 01 '19 at 19:31

0 Answers0