Say I have a controller with an Index() method, and this controller utilizes multiple "Manager classes" that manage certain assets that need to be retrieved with an HttpClient from an API.
I've read that sharing an HttpClient with multiple calls is better than to reinstantiate it with every call to save ports.
I do however want to dispose of the HttpClient before the controller returns the view, because the view contains an entire Knockout/Typescript based front end project that handles the rest of the data (so it's basically only settings and meta data stuff).
Do I need to pass the HttpClient variable to each and every "Manager class", or does it suffice to do something like the following, and use a static HttpClient inside the classes?
public ActionResult Index()
{
using (Globals.Client = new System.Net.Http.HttpClient())
{
// do stuff like SettingManager.GetSetting("settingKey") which uses
// the Globals.Client variable
}
return View();
}
Or should I not even want to dispose the HttpClient in the first place?
HttpClient. We should create a single instance and re-use it. It's counter-intuitive becauseIDisposablemeans we dispose when we're done with it. But if we re-use it then we're never done with it.HttpClientfor, and inject that into your controller. The implementation of that class usesHttpClient. You can register it with DI as a singleton, and that class maintains a single instance ofHttpClient. That kills three birds with one stone: Each individual controller isn't responsible for maintaining the lifetime of the client, there's no "global" client, and the controllers don't depend directly onHttpClientso they're more testable.