What is Autofac's .AddHttpClient equivalent?

68 Views Asked by At

What is the Autofac equivalent of .NET's default .AddHttpClient<>() method? I currently have the code defined below, which works, but it feels a bit off by doing it this way. Is there a better/shorter way to achieve this?

builder.Register(_ => new HttpClient())
    .Named<HttpClient>(nameof(CustomHttpClient));

builder.RegisterType<CustomHttpClient>()
    .As<ICustomHttpClient>()
    .WithParameter(
        (pi, _) => pi.ParameterType == typeof(HttpClient),
        (_, c) => c.ResolveNamed<HttpClient>(nameof(CustomHttpClient)))
    .InstancePerDependency();

For comparison, the default .NET method is:

builder.Services.AddHttpClient<ICustomHttpClient, CustomHttpClient>();

My CustomHttpClient's constructor signature is:

CustomHttpClient(HttpClient httpClient, ILogger<CustomHttpClient> logger, IOptions<MyOptions> options)

Or should I approach this differently? Help is appreciated.

1

There are 1 best solutions below

7
Guru Stron On

Autofac's ContainerBuilder has very useful Populate method (from Autofac.Extensions.DependencyInjection nuget) which allows you to bring registrations from IEnumerable<ServiceDescriptor> (i.e. IServiceCollection), you can try using it:

var services = new ServiceCollection();
services.AddHttpClient<ICustomHttpClient, CustomHttpClient>();

var containerBuilder = new ContainerBuilder();
containerBuilder.Populate(services);
// rest of the registrations and build

This way you will get the "correct" setup which will use IHttpClientFactory with all it's benefits.

See .NET Core section of Autofac docs.

Also note that if you want to use it with standard setup like in ASP.NET Core you can keep the registration with build in DI for simplicity (unless you will overwrite it with Autofac registrations).