静态类中的对象实例

发布于 2024-12-27 22:04:03 字数 733 浏览 4 评论 0原文

我正在开发一个具有多个 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();

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

I am developing a web application with multiple WCF service references. Currently, each time we need to make a call to a service we do the following(as an example):

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

Would it be better to have a static class with static references to each Service and call that class instead, thereby avoiding creating a new instance of the ServiceClient object each time we want to call it?

For example:

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

And, if doing it this way, would the line

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

cause a new object to be created each time we try to call that object, or will it be the same instance of that object every time we make a call to it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

朕就是辣么酷 2025-01-03 22:04:03

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

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();

You can have a class which will have all the functions exposed by your data contract. All these methods will be static. Now inside these function you can do as follows

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();
    }
} 

Consumer will consume it like

var calculatedData = ServiceManager.SomeMethod();
浴红衣 2025-01-03 22:04:03

如果您想这样做,请创建

单例服务

单例服务是终极的共享服务。当服务配置为单例时,所有客户端都会独立连接到同一个已知实例,无论它们连接到服务的哪个端点。单例服务永远存在,并且只有在主机关闭后才会被丢弃。单例仅在创建主机时创建一次。

您可以通过将 InstanceContextMode 属性设置为 InstanceContextMode.Single 来配置单例服务:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class MySingleton : ...
{...}

if you want to do so create

Singleton Service

The singleton service is the ultimate sharable service. When a service is configured as a singleton, all clients independently get connected to the same single well-known instance, regardless of which endpoint of the service they connect to. The singleton service lives forever and is only disposed of once the host shuts down. The singleton is created exactly once, when the host is created.

You configure a singleton service by setting the InstanceContextMode property to InstanceContextMode.Single:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class MySingleton : ...
{...}
白昼 2025-01-03 22:04:03

它只会创建一次,您无法控制它的创建时间。处理此问题的常用方法是创建一个单独的静态方法(例如 init),在其中创建实例,或者在第一次调用时创建它。您应该为此检查单例设计模式

It will only be created once, you will have no control however over when it will be created. The usual way to handle this is either create a seperate static method (init for example) where you create the instance or create it when first called. You should check the singleton design pattern for this.

纵性 2025-01-03 22:04:03

您可以使用如下所示的帮助程序:

private delegate void ServiceAction(Service.ServiceClient client);

private static void PerformServiceAction(ServiceAction serviceAction)
{
  using (var client = new Service.ServiceClient())
  {
    serviceAction(client);
  }
}

然后可以通过以下方式调用它:

Helper.PerformServiceAction(client => client.SomeMethod());

它仍然为每个调用或调用序列创建一个代理,但至少您的调用代码更轻。

(请记住,对 wcf 客户端代理使用“using”并不是一个好主意,因为 dispose 可能会引发异常,因此最好捕获异常并手动优雅地关闭代理)。

You could use a helper like the following:

private delegate void ServiceAction(Service.ServiceClient client);

private static void PerformServiceAction(ServiceAction serviceAction)
{
  using (var client = new Service.ServiceClient())
  {
    serviceAction(client);
  }
}

which can then be invoked the following way:

Helper.PerformServiceAction(client => client.SomeMethod());

It still creates a proxy for every call or sequence of calls but at least your calling code is lighter.

(Keep in mind that using 'using' with a wcf client proxy is not a good idea because dispose might throw an exception so it's better to catch exceptions and to close the proxy gracefully manually).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文