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)