What is the recommendation to reuse GraphServiceClient in Microsoft Graph .Net SDK?

Viewed 3481

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?

1 Answers

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.

Related