0

Using the latest version of RestSharp and the documentation states

Do not instantiate RestClient for each HTTP call. RestSharp creates a new instance of HttpClient internally, and you will get lots of hanging connections, and eventually exhaust the connection pool.

Therefore i already have a Base class which cant be changed that is used by all my MVC Controllers.

I thought i could create my own class but this would mean everytime a page makes a request it would create another instance as i would need to instantiate a new instance.

How could i instantiate a single RestClient so if i have 10 pages making a call it utilises the one instance as per the documentation?

Any examples would be great.

Computer
  • 2,149
  • 7
  • 34
  • 71

1 Answers1

1

Service

I think the best solution could be to have a service that your controllers use to make the rest call and that service will have a single static RestClient.

No DI option, no service option

You could insert a class between the base class and your controllers

class WithRestClient: Base 
{
protected static RestClient = new RestClient  ... (or in the constructor)
}

class Ctrl1: WithRestClient { ...
class Ctrl2: WithRestClient { ...

With DI

You could setup a singleton RestClient in Startup and have that injected into your Controllers as a constructor parameter.

tymtam
  • 31,798
  • 8
  • 86
  • 126
  • Thanks - Im trying the option With DI to start with. Is there a way for me to monitor the Connection pool to see what the count is to ensure it is 1 instance? – Computer Aug 13 '22 at 12:52
  • 1
    You can `Object.ReferenceEquals` to check when debugging.... – tymtam Aug 13 '22 at 13:02