IHttpClientFactory
Фабрика держит общий обработчик,
а не новый сокет на каждый
new HttpClient. В примерах
свой класс реализует
IHttpClientFactory и возвращает
HttpClient
с заглушкой без пакета DI.
Синтаксис
HttpClient client = factory.CreateClient("abcde");
Пример
Давайте создать клиент по имени:
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Factory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
return new HttpClient(new Stub());
}
}
class Program
{
static void Main()
{
IHttpClientFactory factory = new Factory();
HttpClient client = factory.CreateClient("abcde");
bool res = client != null;
Console.WriteLine(res);
client.Dispose();
}
}
Результат выполнения кода:
True
Пример
Давайте скачать текст через фабрику:
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Factory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
return new HttpClient(new Stub());
}
}
class Program
{
static async Task Main()
{
IHttpClientFactory factory = new Factory();
using HttpClient client = factory.CreateClient("abcde");
string res = await client.GetStringAsync(
"http://abcde.example/");
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте создать два клиента одной фабрикой:
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
class Stub : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
return Task.FromResult(response);
}
}
class Factory : IHttpClientFactory
{
public HttpClient CreateClient(string name)
{
return new HttpClient(new Stub());
}
}
class Program
{
static void Main()
{
IHttpClientFactory factory = new Factory();
using HttpClient first = factory.CreateClient("abcde");
using HttpClient second = factory.CreateClient("abcde");
bool res = first != second;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Смотрите также
-
HttpClient,
класс клиента -
Dispose,
закрытие клиента -
GetStringAsync,
текст ответа -
Timeout,
предел ожидания