单例与静态:Web 服务客户端声明的最佳实践
我有 2 个 ASMX 类型的 Web 服务。目前它在 App.cs 中声明为静态。 我在想 Web 服务客户端声明的静态实例和单例实例有什么区别。
在静态中,我需要做的就是创建这个变量
static PreferencesWSSoapClient _preferenceWS;
和一个属性
public static PreferencesWSSoapClient PreferenceWS
{
get
{
if (_preferenceWS == null)
{
_preferenceWS = new PreferencesWSSoapClient("PreferencesWSSoap", PrefUri.ToString());
}
return _preferenceWS;
}
}
。在单例中,我需要创建一个单例类。
问题是Web 服务客户端声明的静态实例和单例实例有什么区别?
Web 服务客户端声明的最佳实践是什么?
I have 2 web services in ASMX type. It is currently declared in App.cs as static.
I am thinking whats the difference between static and singleton instance of web service client declaration.
In static all I need to do is to create this variable
static PreferencesWSSoapClient _preferenceWS;
and a property
public static PreferencesWSSoapClient PreferenceWS
{
get
{
if (_preferenceWS == null)
{
_preferenceWS = new PreferencesWSSoapClient("PreferencesWSSoap", PrefUri.ToString());
}
return _preferenceWS;
}
}
In singleton, I need to create a singleton class.
Question is whats the difference between static and singleton instance of web service client declaration?
What is the best practice of web service client declaration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为每个请求创建一个新的客户端对象会更安全。不仅仅是因为静态 Web 客户端实例的生命周期等于应用程序本身就是一个 evel :) 让我稍微证实一下我的想法。
如果您在 Silverlight 中使用 Web 服务客户端,这意味着您只能在异步模式下使用它。它将需要使用事件处理程序来获取结果。如果应用程序中只有一个客户端实例,则更容易出现事件附加错误(我的意思是,同一侦听器的多个分配可能变得很可能并且经常出现问题)。
It's safer to create a new client object for each request. Not just because a static webclient instance having a lifetime equal to application is an evel itself :) Let me to substantiate my thoughts a bit.
If you use your web service client in Silverlight this means you'll have to use it only in asynchronous mode. It will require using eventhandlers for getting results. And it's be pretty easier to make event attaching mistake if you have only one client instance in the application (I mean here multiple assignments of the same listeners may become quite possible and often issue).