Search code examples
c#.netazureautorest

Should we use Singletons for clients derived from Microsoft.Rest.ServiceClient in C#?


When working with Azure .NET SDKs generated from swagger specs (such as those associated with Azure Resource Manager) the resulting libraries leverage the Microsoft AutoRest Client Runtime and the various "Clients" all inherit from "ServiceClient".

We've been working with DocumentDB Client, and reading a lot about issues with using the native HttpClient in .NET. Microsoft suggests using singleton patterns for both of these clients because of how they work internally, despite the well-known issues with using the singleton pattern. In these cases, it is necessary.

As a result, we've developed a strategy for using and managing singletons for these cases, so we want to know if we should use the same strategy for the Azure REST clients derived from ServiceClient. If it uses HttpClient it would make sense.

Note: This question isn't a question looking for general developer advice about singletons or clients, but rather a specific question for the Microsoft dev teams associated with the AutoRest client runtime based on knowledge of it's inner-workings.


Solution

  • Yes and no. :-) You don't need to use the Singleton design pattern, but it is advisable to share ServiceClient-derived instances wherever possible since each one encapsulates an HttpClient.

    For some Azure libraries, sharing a single client isn't always possible. For example, the SearchIndexClient in the Azure Search library can only target one index at a time, so if your app uses multiple indexes you'll need to pool them somehow. Here is a related question on this topic which has links to other discussions elsewhere.