c# - 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.
解决方案
我有一个类似的问题 - 问题在于双重注册:
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>();
推荐阅读
- ios - 从用户默认值加载数据时,我得到一个空的 CLLocationCoordinates 数组
- tizen - 模拟器管理器未在 Tizen Studio 中启动
- html - 将数组从父组件传递给子角度
- sql - 使用 VBA 或 SQL 将字段格式化为天
- arrays - 提取数组中大于零的值集的索引
- python - Q-learning with experience replay 不学习
- sql - 如何在sql中查找特定单元格的行号和列号?
- html - 具有固定标题和可滚动 xy 正文的 Css 表
- azure - 如何使用 PowerShell 逐行读取 txt/csv
- html - 具有固定标题和 tbody 自动高度的表