处置注入的HttpClient [英] Dispose of Injected HttpClient

查看:326
本文介绍了处置注入的HttpClient的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的MVC应用程序调用使用HttpClient的一个动作的WebAPI。我决定要注入的HttpClient使用StructureMap的,并覆盖处理控制器

Our MVC application calls a WebAPI action using HttpClient. I decided to inject the HttpClient using StructureMap and override dispose in the controller

public HomeController(HttpClient httpClient)
{
    _httpClient = httpClient;
}

protected override void Dispose(bool disposing)
{
   if (disposing && _httpClient != null)
   {
       _httpClient.Dispose();
   }
   base.Dispose(disposing);
}

该StructureMap ObjectInitialize基本上是这样的。

The StructureMap ObjectInitialize basically looks like this..

x.For<HttpClient>().Use(() => new HttpClient() { BaseAddress = "my/uri/"});

当我建立这个,codeAnalysis抱怨失去范围之前释放对象和指向的IoC code。

When I build this, CodeAnalysis complains "Dispose objects before losing scope"and points to the IoC code.

我可以燮preSS的,或者我需要在哪里处置HttpClient的吗?我也试过

Can I Suppress that, or where do I need to dispose of the HttpClient? I also tried

protected void Application_EndRequest(object sender, EventArgs e)
{
    ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
}

但我仍然得到违反规则。

But I still get that rule violation.

推荐答案

HttpClient的处置清理任何活动的取消标记任何部分完成的请求/响应。在大多数情况下的正常处置它不会是必要的,但按照惯例,你应该。要知道,虽然处理的HttpClient将强行关闭TCP连接。

Disposing HttpClient cleans up any active Cancellation tokens and any partially complete requests/responses. Under most normal scenarios disposing it will not be essential, although by convention you should. Be aware though that disposing HttpClient will forcibly close the TCP connection.

如果你的MVC应用程序正在大量调用同一服务器,它可能是值得持有到跨请求HttpClient的实例和重用它。这将避免你不必重新设置默认的请求头每一次,它会允许TCP连接的重用。

If your MVC application is making lots of calls to the same server, it might be worth holding onto the HttpClient instance across requests and reusing it. That will avoid you having to re-setup the default request headers each time and it will allow the reuse of the TCP connection.

这篇关于处置注入的HttpClient的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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