我正在开发一个包含多个 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/