首页 > 解决方案 > Unable to resolve service for type 'System.Net.Http.HttpClient'

问题描述

I created a ViewComponent class which call a REST API using the HttpClient, this is the code:

public class ProductsViewComponent : ViewComponent
{
    private readonly HttpClient _client;

    public ProductsViewComponent(HttpClient client)
    {
        _client = client ?? throw new ArgumentNullException(nameof(client));
    }

    public async Task<IViewComponentResult> InvokeAsync(string date)
    {
        using(var response = await _client.GetAsync($"/product/get_products/{date}"))
        {
            response.EnsureSuccessStatusCode();
            var products = await response.Content.ReadAsAsync<List<Products>>();
            return View(products);
        }
    }
}

I get this error:

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate MyApp.ViewComponents.ProductsViewComponent'

I injected the HttpClient in the ConfigureService method available in Startup in this way:

 services.AddHttpClient<FixturesViewComponent>(options =>
 {
    options.BaseAddress = new Uri("http://80.350.485.118/api/v2");
 });

UPDATE:

I registered the ProductsViewComponent too, same error.

标签: c#asp.netasp.net-core

解决方案


我有一个类似的问题 - 问题在于双重注册:

services.AddHttpClient<Service>();
services.AddSingleton<Service>();  // fixed by removing this line

类似的例子 [只是为了澄清它不是特定于 AddSingleton 的,也与订单无关。]

services.AddScoped<IService, Service>();  // fixed by removing this line
services.AddHttpClient<IService, Service>();

推荐阅读