使用从 HttpClientFactory 注入的 HttpClient 超出范围

问题描述

考虑这个代码

public class ScopedService {
    public readonly HttpClient client;
    public readonly MyHostedService hostedService;

    public ScopedService(HttpClient client,MyHostedService hostedService) {
        this.client = client;
        this.hostedService = hostedService;
    }

    public void LongAsyncoperationWeDontWantToWaitFor()
    {
        var httpTask = client.GetAsync("...");
        hostedService.SaveTaskForProcessSometimeInTheFuture(httpTask);
    }
}

我有一个进行 http 调用的范围服务。我希望在 http 调用完成之前关闭范围。如果我手动创建和处理 httpClient,那么我自己会超出范围。但是因为在这种情况下客户端是依赖注入的,我无法控制它何时被处理。是否会出现在注入的 httpClient 被释放之前上下文无法关闭的情况?

解决方法

您可以注入 IHttpClientFactory 并在需要时使用它来创建 HttpClient。