Dispose of Injected HttpClient

十年热恋 提交于 2019-12-03 09:08:50

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.

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.

The object that triggers the creation of an object is normally the one responsible for disposing it as well. In this case the HttpClient is created by Structuremap via the DependencyResolver or ControllerFactory. There is no easy way to dispose transient objects with Structuremap, so you want to minimize the injections of IDisposable objects, especially transient ones. I think that you should put the creation and disposal in a service and inject that to the controller instead.

ReleaseAndDisposeAllHttpScopedObjects will not work in this case since it only disposes objects configured as HttpScoped, that is objects that are kept during the whole http request.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!