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
我正在尝试使用依赖注入在 ASP.NET Core-6 Web API.
中注册服务
我得到这个界面:
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;
}
还有实现:
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;
}
}
然后对于 DI,我这样做了:
services.AddScoped<IHttpClientService, HttpClientService>();
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
最初,错误是:
InvalidOperationException: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'HttpClientService.Concrete.HttpClientService'.
但是当我添加:
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
变成了:
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
我已经尝试再次检查代码,但无法追踪到错误。我还需要做什么以及如何解决此错误?
谢谢
你能试试这个吗?
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
services.AddScoped<IHttpClientService, HttpClientService>(sp => {
sp.GetRequiredService<IHttpClientFactory>();
});
services.AddHttpClient();
在 Microsoft.Extensions.DependencyInjection
下找到扩展 method。
我正在尝试使用依赖注入在 ASP.NET Core-6 Web API.
中注册服务我得到这个界面:
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;
}
还有实现:
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;
}
}
然后对于 DI,我这样做了:
services.AddScoped<IHttpClientService, HttpClientService>();
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
最初,错误是:
InvalidOperationException: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'HttpClientService.Concrete.HttpClientService'.
但是当我添加:
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
变成了:
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
我已经尝试再次检查代码,但无法追踪到错误。我还需要做什么以及如何解决此错误?
谢谢
你能试试这个吗?
services.AddScoped<IHttpClientFactory, IHttpClientFactory>();
services.AddScoped<IHttpClientService, HttpClientService>(sp => {
sp.GetRequiredService<IHttpClientFactory>();
});
services.AddHttpClient();
在 Microsoft.Extensions.DependencyInjection
下找到扩展 method。