我们是否应该对从C#中的Microsoft.Rest.ServiceClient派生的客户端使用Singletons? [英] Should we use Singletons for clients derived from Microsoft.Rest.ServiceClient in C#?

查看:37
本文介绍了我们是否应该对从C#中的Microsoft.Rest.ServiceClient派生的客户端使用Singletons?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用从大量规范(例如与Azure Resource Manager关联的规范)生成的Azure .NET SDK时,所得库将利用Microsoft AutoRest客户端运行时,并且各种客户端"都继承自"ServiceClient".

我们一直在使用DocumentDB Client,并阅读了许多有关在.NET中使用本机HttpClient的问题.微软建议为这两个客户端使用单例模式,因为它们在内部工作,尽管使用单例模式存在众所周知的问题.在这种情况下,有必要.

因此,我们针对这些情况制定了使用和管理单例的策略,因此我们想知道是否应该对源自ServiceClient的Azure REST客户端使用相同的策略.如果使用HttpClient,那将是有道理的.

注意:此问题不是寻找有关单例或客户端的一般开发人员建议的问题,而是针对基于AutoRest客户端运行时的内部工作知识的Microsoft开发团队的特定问题.

解决方案

是,不是.:-)您不需要使用Singleton设计模式,但建议尽可能共享源自 ServiceClient 的实例,因为每个实例都封装了 HttpClient .

对于某些Azure库,并非总是可以共享一个客户端.例如,Azure搜索库中的 SearchIndexClient 一次只能定位一个索引,因此,如果您的应用程序使用多个索引,则需要以某种方式合并它们.这是与此主题相关的问题链接到其他地方的其他讨论.

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.

解决方案

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.

这篇关于我们是否应该对从C#中的Microsoft.Rest.ServiceClient派生的客户端使用Singletons?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆