在单例服务中使用HttpClientFactory是不是有错?

问题描述 投票:0回答:1

我读了这篇关于 HttpClientFactory 的文章。但我找不到我的问题的答案。在单例服务中使用 HttpClientFactory 将请求发送到某个地方是不是不好的方法?

我的程序.cs:

builder.Services.AddSingleton<TestService>();
builder.Services.AddTransient<HttpRequestDelegatingHandler>();


builder.Services.AddHttpClient("test", client =>
{
    client.BaseAddress = new Uri("https://jsonplaceholder.typicode.com");
}).AddHttpMessageHandler<HttpRequestDelegatingHandler>();

我的测试服务:

public class TestService
{
    public Guid InstanceId { get; } = Guid.NewGuid();

    private readonly **IHttpClientFactory _factory;**
    private readonly ILogger<TestController> _logger;

     public TestService(IHttpClientFactory factory, ILogger<TestController> logger)
    {
        **_factory = factory;**
        _logger = logger;
    }

    public async Task<string> GetAsync()
    {
        // Get the scoped service's ID
        _logger.LogInformation("Service ID in controller {InstanceId}", InstanceId);

        // Retrieve an instance of the test client, and send a request
        var client = _factory.CreateClient("test");
        var result = await client.GetAsync("posts");

        // Just return a response, we're not interested in this bit for now
        result.EnsureSuccessStatusCode();
        return await result.Content.ReadAsStringAsync();
    }
} 

我创建了一个委托处理程序来了解发生了什么,但我没有注意到任何问题。

.net dependency-injection
1个回答
0
投票

IHttpClientFactory
服务中使用
Singleton
是可以的,顺便说一句,客户端工厂创建的所有
HttpClient
实例都应该是
short-lived
,那么最好使用
using
语句,例如这个:

public async Task<string> GetAsync()
    {
        //...

        // make sure the httpclient will be disposed
        using var client = _factory.CreateClient("test");
        var result = await client.GetAsync("posts");

        // ...
    }
© www.soinside.com 2019 - 2024. All rights reserved.