[英]Can I use HttpClientFactory in a .NET.core app which is not ASP.NET Core?
我已阅读有关使用 HttpClientFactory 的流行博客文章https://www.stevejgordon.co.uk/introduction-to-httpclientfactory-aspnetcore
引用它
ASP.NET Core 2.1 中即将推出一项新的 HttpClientFactory 功能,该功能有助于解决开发人员在使用 HttpClient 实例从其应用程序发出外部 Web 请求时可能遇到的一些常见问题。
所有示例都显示在 asp.net 应用程序的启动类中连接它,例如
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddHttpClient();
}
我的问题是您可以在 ASP.NET 核心之外使用吗? 如果是这样,有没有例子
我原以为很多非 Web 应用程序(.net 核心应用程序)需要进行 Web 调用,那么为什么这不是 .net core api 的一部分,而不是放入 asp.net core api
根据文档HttpClientFactory 是 .Net Core 2.1 的一部分,因此您不需要 ASP.NET 来使用它。 而且还有被描述为使用一些方法。 最简单的方法是使用 Microsoft.Extensions.DependencyInjection 和AddHttpClient
扩展方法。
static void Main(string[] args)
{
var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
var httpClientFactory = serviceProvider.GetService<IHttpClientFactory>();
var client = httpClientFactory.CreateClient();
}
感谢您的回复。
因此可以在控制台应用程序中使用。
有几种方法可以做到这一点,这取决于你想要走的路。 这里有2个:
直接添加到 ServiceCollection 例如 services.AddHttpClient()
使用通用主机,例如在 .ConfigureServices() 方法中添加 httpclientFactory
有关在控制台应用程序中使用的博客文章,请参阅此处
正如其中一个答案所暗示的那样,
你不需要 ASP.NET 来使用它
但是,您需要做一些工作才能将其放入依赖注入 (DI) 中:
安装microsoft.extensions.http (与ASP.NET无关)
配置 DI 时,请使用此扩展。 它注册了builders/httpclientFactory/...(在github上查看它的源代码)
ServiceCollections.AddHttpClient();
如果您想使用不同的名称/设置注册 HttpClient 以与不同的 Web 服务器进行通信(不同的设置,例如:不同的基本网址)
ServiceCollection.AddHttpClient( "yourClientName", x => x.BaseAddress = new Uri("http://www.mywebserver.com"))
如果您想添加 DelegateHendlers,您需要将它添加到您的 httpClient 和您的 DI 容器中。
ServiceCollection .AddHttpClient(clientName, x => x.BaseAddress = new Uri("http://www.google.com")) .AddHttpMessageHandler<DummyDelegateHandler>(); ServiceCollection.AddScoped<DummyDelegateHandler>();
注册您的 HttpClient 以使用 HttpClientFactory
ServiceCollection.AddScoped<HttpClient>(x => x.GetService<IHttpClientFactory>().CreateClient("yourClientName"));
解析http客户端:
var client = ServiceProvider.GetService<HttpClient>();
仅在接受的答案中提供第一种建议方法的示例代码:
services.AddHttpClient<IFoo, Foo>(); // where services is of type IServiceCollection
你的班级看起来像:
public class Foo : IFoo
{
private readonly HttpClient httpClient;
public Consumer(HttpClient httpClient)
{
this.httpClient = httpClient;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.