【发布时间】:2020-07-30 21:33:36
【问题描述】:
我有以下通用类和接口实现
public interface IHttpClient<T> where T : class
{
public Task<List<T>> GetJsonAsync(string url);
}
public class HttpClient<T> : IHttpClient<T> where T:class
{
private readonly IHttpClientFactory _clientFactory;
public HttpClient(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task<List<T>> GetJsonAsync(string url)
{
var request = new HttpRequestMessage(HttpMethod.Get,url);
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<List<T>>(result);
}
return null;
}
}
这就是我尝试在 startup.cs 中注册它们的方式
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(typeof(IHttpClient<>), typeof(HttpClient<>));
}
我的控制器:
private readonly IHttpClient<Feed> _feedClient;
public HomeController( IHttpClient<Feed> _client)
{
_feedClient = _client;
}
这是我遇到的错误
InvalidOperationException:尝试激活时无法解析“System.Net.Http.IHttpClientFactory”类型的服务...
我错过了什么?任何帮助都非常感谢..
【问题讨论】:
-
好像你没有在 IoC 中注册你的
IHttpClientFactory -
另加
services.AddHttpClient(); -
谢谢Knoop,添加代码后运行顺利=))
标签: c# asp.net-core interface