8

I realized Microsoft Graph .Net SDK is using HttpClient class.

https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/src/Microsoft.Graph.Core/Requests/HttpProvider.cs

Microsoft's own documentation recommends reuse of HttpClient instances as much as possible instead of spinning up a new instance per request which may lead to exhausting the connection pool and SocketExceptions eventually.

Is there a similar recommendation, to reuse GraphServiceClient as much as possible? Is there any particular concern with instantiating a new GraphServiceClient per request?

Dogu Arslan
  • 3,292
  • 24
  • 43

1 Answers1

14

I am not aware of any recommendation, but if you look at the code from both the GraphServiceClient as the underlying BaseClient, there is not state kept. Only the incoming or defaulted HttpProvider, and there is the problem. If you rely on the GraphServiceClient generating a new HttpProvider (and thus a new HttpClient) each and every time, you have the same problem as with creating multiple HttpClient instances.

So if you are recreating clients, you should at least provide it with a cached HttpProvider. And then, it doesn't hurt much to keep the entire client in cache.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 1
    Yup. Same rules as HttpClient. Try and reuse the instance so that we can take advantage of existing TCP connections. – Darrel Miller Sep 15 '18 at 13:49
  • 3
    This saved my life :) My api performance got improved by ~50% after i am using HttpProvider as a singleton object. – SanjayD Jan 03 '19 at 19:42