简体   繁体   中英

disposing httpClient in aspnetcore mvc controller

I am creating a new Asp.Net Core (net standard 2) Mvc controller that uses a WebAPI (REST) call to obtain the data. I was following many of the examples shown all over the Interweb from both microsoft and non-microsoft sources. These all use the "standard" using(var client = new HttpClient()) construct.
However, then read the documentation for HttpClient

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.

This got me thinking, do I create a scoped instance and add it to DI, or follow their example on the same page, and create a static instance on the controller? If a static instance, how do I dispose it?

Alternately, can anyone point me to a production ready MVC wrapper for a standard CRUD view implementation?

If you have not read "You're using HttpClient wrong and it is destabilizing your software" .

If you have any kind of load at all you need to remember these two things:

  1. Make your HttpClient static.
  2. Do not dispose of or wrap your HttpClient in a using unless you explicitly are looking for a particular behavior (such as causing your services to fail).

I agree with mike z DI can be used in this case.

eg SimpleInjector's Singleton is taking care of disposing.

Simple Injector guarantees that instances are disposed in opposite order of creation.


If you still want to wrap it, look at "Generic wrapper for calling ASP.NET WEB API REST service using HttpClient with optional HMAC authentication"

Upd: Make sure you dispose of instances of both of HttpRequestMessage and HttpResponseMessage . See example of usage

Source: http://faithlife.codes/blog/2017/03/usage-guidelines-for-httpclient/

For anyone using .net core 2.1 or greater it is recommended to use HttpClientFactory

To address those mentioned issues and make the management of HttpClient instances easier, .NET Core 2.1 introduced a new HttpClientFactory that can also be used to implement resilient HTTP calls

See microsoft docs on how it can be leveraged.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM