Quantcast
Channel: Unable to resolve service for type 'System.Net.Http.HttpClient' - Stack Overflow
Viewing all articles
Browse latest Browse all 9

Unable to resolve service for type 'System.Net.Http.HttpClient'

$
0
0

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.


Viewing all articles
Browse latest Browse all 9

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>