处置注入的HttpClient

编程入门 行业动态 更新时间:2024-10-26 04:20:06
本文介绍了处置注入的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

本文发布于:2023-11-08 22:07:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1570581.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!