我需要在 ASP.NET 中处理 Web 服务引用吗? [英] Do I need to dispose a web service reference in ASP.NET?

查看:17
本文介绍了我需要在 ASP.NET 中处理 Web 服务引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

垃圾收集器是否会清理 Web 服务引用,或者我是否需要在调用完我调用的任何方法后对服务引用调用 dispose?

Does the garbage collector clean up web service references or do I need to call dispose on the service reference after I'm finished calling whatever method I call?

推荐答案

不用担心处理您的 Web 服务,您可以只保留每个 Web 服务的一个实例,使用 单例模式.Web 服务是无状态的,因此它们可以在 Web 服务器上的连接和线程之间安全地共享.

Instead of worrying about disposing your web services, you could keep only a single instance of each web service, using a singleton pattern. Web services are stateless, so they can safely be shared between connections and threads on a web server.

这是一个 Web 服务类的示例,您可以使用它来保存对 Web 服务实例的引用.这个单例是惰性且线程安全的.建议如果你让你的单例懒惰,它们也可以通过遵循相同的逻辑来保持线程安全.要了解有关如何执行此操作的更多信息,请阅读关于实施单例的 C# 深入文章.

Here is an example of a Web Service class you can use to hold references to your web service instances. This singleton is lazy and thread-safe. It is advised that if you make your singletons lazy, they are also kept thread safe by following the same logic. To learn more about how to do this, read the C# In Depth article on Implementing Singletons.

另请记住,您可能会遇到 WCF Web 服务的问题.我建议阅读 WCF 的实例管理技术文章,特别是单例部分,了解更多详情.

Also keep in mind that you may run into issues with WCF web services. I'd recommend reading up on WCF's instance management techniques article, specifically the singleton section, for more details.

public static class WS
{
    private static object sync = new object();
    private static MyWebService _MyWebServiceInstance;

    public static MyWebService MyWebServiceInstance
    {
        get
        {
            if (_MyWebServiceInstance == null) 
            {
              lock (sync)
              {
                if (_MyWebServiceInstance == null)
                {
                    _MyWebServiceInstance= new MyWebService();
                }
              }
            }
            return _MyWebServiceInstance;
        }
    }
}

然后当您需要访问您的网络服务时,您可以这样做:

And then when you need to access your web service, you can do this:

WS.MyWebServiceInstance.MyMethod(...)

var ws = WS.MyWebServiceInstance;
ws.MyMethod(...)

我已经在多个项目中成功地使用了这种模式并且效果很好,但是正如 tvanfosson 在下面的评论中提到的那样,更好的策略是使用 DI 框架来管理您的 Web 服务实例.

I've successfully used this pattern on several projects and it has worked well, but as tvanfosson mentions in the comments below, an even better strategy would be to use a DI framework to manage your web service instances.

这篇关于我需要在 ASP.NET 中处理 Web 服务引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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