Scrutor
Scrutor copied to clipboard
Support for AddHttpClient
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! 🙂
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;
- I'd have to add a new dependency;
Microsoft.Extensions.Http - 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.
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 😅
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.