Scrutor icon indicating copy to clipboard operation
Scrutor copied to clipboard

Support for AddHttpClient

Open jasontaylordev opened this issue 3 years ago • 3 comments

Just wondering if there is currently any way to support registration of Typed clients? For example:

services.AddHttpClient<ICatalogService, CatalogService>();

Use IHttpClientFactory to implement resilient HTTP requests | Microsoft Docs

The implementation might look something like this:

builder.Services.Scan(scan => scan
    .FromAssemblyOf<ICatalogService>()
    .AddClasses()
    .AsImplementedInterfaces()
    .WithHttpClient());

Thanks! 🙂

jasontaylordev avatar Aug 16 '22 23:08 jasontaylordev

Hi @jasontaylordev! 👋🏻

It could technically be accomplished using an existing extensibility point, RegistrationStrategy:

using Microsoft.Extensions.DependencyInjection;

namespace Scrutor;

public static class HttpClientExtensions
{
    public static IServiceTypeSelector WithHttpClient(this IServiceTypeSelector selector)
    {
        return selector.UsingRegistrationStrategy(HttpClientRegistrationStrategy.Instance);
    }

    private class HttpClientRegistrationStrategy : RegistrationStrategy
    {
        public static readonly RegistrationStrategy Instance = new HttpClientRegistrationStrategy();

        public override void Apply(IServiceCollection services, ServiceDescriptor descriptor)
        {
            // TODO: Implement call to AddHttpClient, based on descriptor, using reflection...
            // services.AddHttpClient<TClient, TImplementation>();
        }
    }
}

...but there's a couple of reasons why shipping something like this out-of-the-box is problematic;

  1. I'd have to add a new dependency; Microsoft.Extensions.Http
  2. There's no non-generic overload of AddHttpClient, so I'd have to use some ugly reflection (MakeGenericMethod) for each type combination you'd want to register. This will be both slow and lead to some code I don't want to maintain 😅

Also, quite often, you'd want to configure the HttpClient instance, using the Action<HttpClient> parameter. I guess you could pass it to the registration strategy, but that would lead all the configured instances to getting the same configuration. At that point, I don't see much value in scanning and registering based on convention.

khellang avatar Aug 17 '22 14:08 khellang

2. There's no non-generic overload of AddHttpClient

If you could convince Microsoft to add this, it would be pretty easy to write, but looking at the code, the generic seems to go pretty deep, so it might be a hard ask 😅

khellang avatar Aug 17 '22 14:08 khellang

No matter the implementation, this would be a nice thing to have as we too have several registrations done via AddHttpClient and all the rest is managed by Scrutor.

mmajcica avatar Sep 29 '22 06:09 mmajcica