是否应该处理由HttpClientFactory创建的HttpClient实例? [英] Should HttpClient instances created by HttpClientFactory be disposed?

查看:128
本文介绍了是否应该处理由HttpClientFactory创建的HttpClient实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我已经在我的Startup.cs中使用服务集合注册了一个命名客户端:

So, I've registered a named client with the services collection in my Startup.cs:

services.AddHttpClient(someServiceName, 
                       client => client.BaseAddress = baseAddress);

现在可以从我的计算机中注入 IHttpClientFactory 服务提供商。

and now can inject an IHttpClientFactory from my service provider.

使用此 IHttpClientFactory ,我可以想到一个客户端实例:

Using this IHttpClientFactory, I conjure up a client instance:

var client = httpClientFactory.CreateClient(someServiceName)

从前,有必要非常小心地处置 HttpClient 实例,因为它是很少要做的事

Once upon a time, it was necessary to be very careful about the disposing of HttpClient instances, as it was rarely the right thing to do.

但是,现在我们有了 HttpClientFactory ,这又有关系吗?应该/可以不用担心处置此客户端吗?例如

However, now we have HttpClientFactory, does this matter any more? Should/Can this client be disposed without worry? e.g.

using (var httpClient = httpClientFactory.CreateClient(someServiceName))
using (var response = await httpClient.PostAsync(somePath, someData))
{
    var content = await response.Content.ReadAsAsync<SomeResponse>();
    //...
}


推荐答案

不。您不应该处置您的客户。更笼统地说,您不应处理通过DI容器检索的任何内容,DI容器在ASP.NET Core中默认为服务集合。生命周期是由DI容器管理的,因此,如果您处置客户端,但随后将其注入某些对象中,则会得到 ObjectDisposedException 。让容器处理垃圾。

No. You should not dispose of your client. To be more general, you should not dispose of anything retrieved via a DI container, which in ASP.NET Core is by default the service collection. The lifetime is managed by the DI container, so if you dispose of the client, but it's later injected into something, you'll get an ObjectDisposedException. Let the container handle disposal.

这实际上是与 IDisposable 类的常见混淆。如果您的类本身拥有依赖项,则您个人应该只实现 IDisposable 。如果所有依赖项都是 injected 注入的,则不应实现 IDisposable ,因为它不拥有任何需要处置的东西。同样,您不应处置注入类中的任何东西,因为它不拥有那些依赖项。只处理您专门处理的新事物。如果您没有看到关键字 new ,则可能不应该进行处理。

This is actually a common confusion with IDisposable classes. You should personally only implement IDisposable if your class itself owns dependencies. If all its dependencies are injected, you should not implement IDisposable, since it doesn't own anything that needs disposal. Likewise, you should not dispose of anything injected into your class, as it doesn't own those dependencies. Only dispose of things you specifically new up. If you don't see the keyword new, you probably shouldn't be disposing.

这篇关于是否应该处理由HttpClientFactory创建的HttpClient实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆