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.
Autofac's
ContainerBuilderhas very usefulPopulatemethod (fromAutofac.Extensions.DependencyInjectionnuget) which allows you to bring registrations fromIEnumerable<ServiceDescriptor>(i.e.IServiceCollection), you can try using it:This way you will get the "correct" setup which will use
IHttpClientFactorywith 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).