1

So I'm working on a personal project, which I'm building using entity framework. I've decided on using API's as the service layer instead of a more traditional MVC architecture (but not SPA either). I also don't want to expose the API to the client, so instead of doing the calls with javascript, I am using HttpClient. However, I understand from documentation that the HttpClient is designed to be created once and re-used for the life of the application, but I'm not sure exactly how to do that. So here's what I'm doing: I have the view (a dashboard), a controller (where I'm making the HttpClient calls), and a view model. I've only built the one view where it's consuming the API, but what If I had multiple views calling multiple API's with more than one controller (i.e. different areas of the site)? What is the best way to create a single instance of HttpClient and use it across multiple controllers? Should I initialize it like ApplicationDBContext or should I create a custom controller and have all of the controllers calling API's inherit from that custom controller? I'm probably getting into some fundamental things but there are gaps in my knowledge that I'm trying to fill.

Thanks!

lrossignol
  • 43
  • 7
  • Create a wrappper class for `HttpClient` and make it singleton. As it's a singleton, it's instantiated inside that singleton class and exposed that only instance always. You can access that instance in all controllers. If you are considering multithreading or Async then handle the race condition. – Venkata Dorisala May 17 '17 at 15:49
  • I had read about using a singleton solution here which kinda pushed me away from it, but I don't know enough to know if there's a problem with doing it that way or not. http://stackoverflow.com/questions/40228146/httpclient-singleton-implementation-in-asp-net-mvc – lrossignol May 17 '17 at 16:07

0 Answers0