如何将类型化 IHttpClientFactory 与 Autofac 结合使用(使用 .NET 8)?

问题描述 投票:0回答:1

我正在尝试将 Typed HttpClient 与 Autofac 一起使用。但我无法让它发挥作用。

public class MainViewModel
{
   public MainViewModel(MoviesApiClient moviesApiClient, IHttpClientFactory httpClientFactory)
   {            
   }
}

public class MoviesAPIClient
{
    private HttpClient _client;

    public MoviesAPIClient(HttpClient client)
    {
        _client = client;
        _client.BaseAddress = new Uri("http://localhost:5001");
    }
}
var builder = new ContainerBuilder();            
builder.Register(ctx =>
{
  var services = new ServiceCollection();
  services.AddHttpClient<MoviesAPIClient>(configureClient =>{});
  var provider = services.BuildServiceProvider();
  return provider.GetRequiredService<IHttpClientFactory>();
});

 builder.RegisterType<MainWindow>().AsSelf();
 builder.RegisterType<MainViewModel>().AsSelf();
 return builder.Build();

有人可以建议解决方案以使其发挥作用吗?

c# autofac ihttpclientfactory
1个回答
0
投票

我通过返回正确的类型客户端“MoviesAPIClient”来修复它

builder.Register(ctx =>
{
  var services = new ServiceCollection();
  services.AddHttpClient<MoviesAPIClient>(configureClient =>{});
  var provider = services.BuildServiceProvider();
  return provider.GetRequiredService<MoviesAPIClient>();
});
© www.soinside.com 2019 - 2024. All rights reserved.