Search code examples
c#autofacdotnet-httpclientihttpclientfactory

How to use IHttpClientFactory with Autofac (using net framework)?


I am struggling to get the DI to work for IHttpClientFactory in autofac.

Usually I work with the .net core dependency injection system and I do this:

services.AddHttpClient(HttpClientConstants.HttpClientNameA, client =>
            {
                client.BaseAddress = new Uri(MyConfig.MyBaseUrl);
            });

But, now I am working with a Net framework project that uses Autofac. I have looked in internet and as per the tutorials I have found I have tried this:

builder.Register(ctx => new HttpClient() { BaseAddress = new Uri(MyConfig.MyBaseUrl) })
                .Named<HttpClient>(HttpClientConstants.HttpClientNameA)
                .SingleInstance();

            builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient())
            .As<HttpClient>();
builder.RegisterType<MyService>().As<IMyService>();

But when I try to use it like that it crashes on me, and I get an Autofac error stating that it cannot find a constructor to build my service.

public class MyService: IMyService
    {
        
        private readonly IHttpClientFactory httpClientFactory;

        public MyService(IHttpClientFactory httpClientFactory)
        {
            this.httpClientFactory = httpClientFactory; 
        }
    }

Any idea how can I get it work? It is even possible or shouldn´t I use the IHttpClientFactory at all and use a different approach? (like injecting the httpclient directly int he constructor)


Solution

  • I've succeed to register the factory within a .netStandard 2.0 lib this way :

    containerBuilder.Register<IHttpClientFactory>(_ =>
                {
                    var services = new ServiceCollection();
                    services.AddHttpClient();
                    var provider = services.BuildServiceProvider();
                    return provider.GetRequiredService<IHttpClientFactory>();
                });
    

    The ServiceCollection is in the namespace 'Microsoft.Extensions.DependencyInjection' that should be available in .net framework using this nuget package.