简体   繁体   English

ASP.NET Core Web API - 无法为服务类型实例化实现类型“System.Net.Http.IHttpClientFactory”

[英]ASP.NET Core Web API - Cannot instantiate implementation type 'System.Net.Http.IHttpClientFactory' for service type

I am trying to use Dependency Injection to register service in ASP.NET Core-6 Web API.我正在尝试使用依赖注入在 ASP.NET Core-6 Web API 中注册服务。

I got this interface:我得到了这个界面:

public interface IHttpClientService
{
    Task<TRes> PostRequestAsync<TReq, TRes>(string baseUrl, string requestUrl, TReq requestModel, string token = null)
        where TRes : class
        where TReq : class;
    Task<TRes> GetRequestAsync<TRes>(string baseUrl, string requestUrl, string token = null)
        where TRes : class;
}

and also the implementation:以及实施:

public class HttpClientService : IHttpClientService
{
    private readonly IHttpClientFactory _clientFactory;

    public HttpClientService(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    public async Task<TRes> GetRequestAsync<TRes>(string baseUrl, string url, string token = null) where TRes : class
    {
        var client = CreateClient(baseUrl, token);
        var request = new HttpRequestMessage(HttpMethod.Get, url);
        return await GetResponseResultAsync<TRes>(client, request);
    }

    public async Task<TRes> PostRequestAsync<TReq, TRes>(string baseUrl, string url, TReq requestModel, string token = null)
        where TRes : class
        where TReq : class
    {
        var client = CreateClient(baseUrl, token);
        var request = new HttpRequestMessage(HttpMethod.Post, url)
        {
            Content = new StringContent(JsonConvert.SerializeObject(requestModel), null, "application/json")
        };
        return await GetResponseResultAsync<TRes>(client, request);
    }

    private async Task<TRes> GetResponseResultAsync<TRes>(HttpClient client, HttpRequestMessage request) where TRes : class
    {
        var response = await client.SendAsync(request);
        var responseString = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<TRes>(responseString);
        return response.IsSuccessStatusCode ? result : throw new ArgumentException(response.ReasonPhrase);
    }
    private HttpClient CreateClient(string baseUrl, string token)
    {
        var client = _clientFactory.CreateClient();
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.BaseAddress = new Uri(baseUrl);
        if (!string.IsNullOrEmpty(token))
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        }
        return client;
    }
}

Then for the DI, I did this:然后对于 DI,我这样做了:

services.AddScoped<IHttpClientService, HttpClientService>();
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();

Initially, the error was:最初,错误是:

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'HttpClientService.Concrete.HttpClientService'.

But when I added:但是当我添加时:

services.AddScoped<IHttpClientFactory, IHttpClientFactory>();

It became:它变成了:

System.ArgumentException
  HResult=0x80070057
  Message=Cannot instantiate implementation type 'System.Net.Http.IHttpClientFactory' for service type 'System.Net.Http.IHttpClientFactory'.
  Source=Microsoft.Extensions.DependencyInjection
  StackTrace:
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.Populate()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory..ctor(ICollection`1 descriptors)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider..ctor(ICollection`1 serviceDescriptors, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection services, ServiceProviderOptions options)
   at Microsoft.Extensions.DependencyInjection.DefaultServiceProviderFactory.CreateServiceProvider(IServiceCollection containerBuilder)
   at Microsoft.Extensions.Hosting.Internal.ServiceFactoryAdapter`1.CreateServiceProvider(Object containerBuilder)
   at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
   at Microsoft.Extensions.Hosting.HostBuilder.Build()
   at Microsoft.AspNetCore.Builder.WebApplicationBuilder.Build()
   at Program.<<Main>$>d__0.MoveNext() in C:\MyApp.WebApi\Program.cs:line 165

I have tried to check the code again, but couldn't trace the error.我试图再次检查代码,但无法追踪错误。 What else do I need to do and how do I resolve this error?我还需要做什么以及如何解决此错误?

Thanks谢谢

services.AddHttpClient();

Microsoft.Extensions.DependencyInjection下找到的扩展方法

Can you try this?你能试试这个吗?

services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
services.AddScoped<IHttpClientService, HttpClientService>(sp => {
  sp.GetRequiredService<IHttpClientFactory>();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 没有“System.Net.Http.IHttpClientFactory”类型的注册服务 - There is no registered service of type 'System.Net.Http.IHttpClientFactory 尝试激活服务时无法解析类型“System.Lazy`1[System.Net.Http.IHttpClientFactory]”的服务 - Unable to resolve service for type 'System.Lazy`1[System.Net.Http.IHttpClientFactory]' while attempting to activate service ASP.NET Core Web API - 无法隐式转换类型&#39;System.Threading.Tasks.Task<Merchant?> &#39;到&#39;商人&#39; - ASP.NET Core Web API - Cannot implicitly convert type 'System.Threading.Tasks.Task<Merchant?>' to 'Merchant' ASP.NET Core DI:如果将作用域服务注册为服务类型和实现类型,则解析相同的实例 - ASP.NET Core DI: Resolve same instance if scoped service is registered both as service type and implementation type 不支持的媒体类型 ASP.NET Core Web API - Unsupported media type ASP.NET Core Web API ASP.NET 核心 Web API 不支持的媒体类型 - ASP.NET Core Web API unsupported Media type ASP.NET Core 类型化客户端中的 IHttpClientFactory - IHttpClientFactory in ASP.NET Core Typed Clients 统一的ASP.NET Web API无法构造字符串类型 - Asp.net web api with unity The type String cannot be constructed ASP.NET Web服务参数类型 - ASP.NET web service parameter type 简单 ASP.NET 核心 Web API - 无法隐式转换类型 system.threading.tasks.task<microsoft.aspnetcore.mvc.iaction></microsoft.aspnetcore.mvc.iaction> - Simple ASP.NET Core Web API - cannot implicitly convert type system.threading.tasks.task<microsoft.aspnetcore.mvc.IAction>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM