Reputation: 270
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?
Upvotes: 1
Views: 2091
Reputation: 18059
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.
Upvotes: 1
Reputation: 601
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:
- Make your HttpClient static.
- 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.
e.g. 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/
Upvotes: 4