【问题标题】:Generic Interface Dependency injection in .Net Core.Net Core 中的通用接口依赖注入
【发布时间】: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


【解决方案1】:

你应该像这样在启动类中注册HttpClient

//register
services.AddHttpClient();

使用

public YourController(IHttpClientFactory httpClientFactory)
{ 
    _httpClientFactory = httpClientFactory;
}
var client = _httpClientFactory.CreateClient();

其他选项

//register
services.AddHttpClient("YourClientName", c =>
{
    c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    c.BaseAddress = new Uri("https://yoururl");
});

使用

public YourController(IHttpClientFactory httpClientFactory)
{ 
    _httpClientFactory = httpClientFactory;
}
var client = _httpClientFactory.CreateClient("YourClientName");

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2019-04-13
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2020-09-12
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多