Reputation: 227
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)
Upvotes: 3
Views: 6602
Reputation: 1442
A cleaner way would be the following:
// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
}
Then register like this:
builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient())
.As<HttpClient>().SingleInstance();
Now you will have both IHttpClientFactory
registered and every HttpClient
is automatically resolved from the IHttpClientFactory
Upvotes: -1
Reputation: 66
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.
Upvotes: 4