我是否需要处置的ASP.NET Web服务的参考? [英] Do I need to dispose a web service reference in ASP.NET?

查看:139
本文介绍了我是否需要处置的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服务的一个实例,使用的 Singleton模式。 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
        {
            lock (sync)
            {
                if (_MyWebServiceInstance == null)
                {
                    _MyWebServiceInstance= new MyWebService();
                }
            }
            return _MyWebServiceInstance;
        }
    }
}

然后当你需要访问Web服务,你可以这样做:

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天全站免登陆