c# - 静态类中的对象实例

标签 c# wcf service-reference

我正在开发一个包含多个 WCF 服务引用的 Web 应用程序。目前,每次我们需要调用服务时,我们都会执行以下操作(作为示例):

Service.ServiceClient ServiceClient = new Service.ServiceClient();
ServiceClient.SomeMethod();

是否有一个静态类对每个服务进行静态引用并改为调用该类,从而避免每次我们想调用它时都创建一个新的 ServiceClient 对象实例?

例如:

public static class Services
{
    private static Service.ServiceClient _ServiceClient = new Service.ServiceClient();
    public Service.ServiceClient ServiceClient
    {
        get
        {
            return _ServiceClient;
        }
    }
}

而且,如果这样做,这条线会不会

private static Service.ServiceClient _ServiceClient = new Service.ServiceClient();

每次我们尝试调用该对象时都会创建一个新对象,还是每次我们调用它时它都是该对象的同一个实例?

最佳答案

您可以拥有一个类,该类将具有您的数据协定公开的所有功能。所有这些方法都是静态的。现在,在这些函数中,您可以执行以下操作

public class ServiceManager{
    public static CalculatedData SomeMethod()
    {
         var client = GetClient();
         try
         {
             return client.SomeMethod();
         }
         catch(Exception ex)
         {
             //Handle Error
         }
         finally
         {
             if(client.State == System.ServiceModel.CommunicationState.Opened)
                client.Close();
         } 

    }
    private static SomeClient GetClient()
    {
         return new ServiceClient();
    }
} 

消费者会喜欢消费它

var calculatedData = ServiceManager.SomeMethod();

关于c# - 静态类中的对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8939541/

相关文章:

c# - 不同 Windows PC 上的多个进程应如何同时使用存储在共享目录中的文件?

wcf - 使用 WCF HTTPS 终结点从控制台应用程序调用 Service Fabric 服务

测试中看到的 WCF 位置

multithreading - WCF Operation.Context 不是线程安全的?

visual-studio-2010 - 添加服务引用错误 "Cannot import wsdl:portType"

WCF 错误 - Reference.cs 为空(空)

c# - WPF ListBox 属性绑定(bind)不更新

c# - ILMerged 后控制台应用程序不再有控制台

c# - 从 Oracle 的 RAW(16) 转换为 .NET 的 GUID