3

我编写了一个具有一些常规功能(添加用户、删除、搜索、更新...)的 WCF 服务。此功能的实现是在实体框架中(使用 sql DB)。

现在我想在客户端使用它。我有一些基本问题:

  1. 我在客户端有很多对 WCF 方法的调用 - 我应该在每次调用时都尝试捕获吗?
  2. 每次我想调用一个方法时,例如 AddUser(User user),我都需要创建一个我的服务实例,如下所示:

    WcfService client = new WcfService();
    client.AddUser(user);
    

    在另一个地方我写道:

    WcfService client = new WcfService(); //Again making a new instance...
    client.UpdateUser(user);
    

我应该为我的 wcf 服务的所有应用程序创建一个实例吗?或者每次在调用方法之前创建一个新实例?(如我上面的例子)。

非常感谢 !

4

2 回答 2

6

In many cases, you want to reuse the same client proxy, as this connection method yields the best performance. Reusing the same proxy can be particularly beneficial if you use security features, which have a high initial security negotiation cost. Note: you surely need to check the state of the client proxy before using.

In the event that reusing the same client proxy is not an option, then consider using a ChannelFactory proxy that uses caching.

The following link provides a good explanation along with best practice recommendations: http://blogs.msdn.com/b/wenlong/archive/2007/10/27/performance-improvement-of-wcf-client-proxy-creation-and-best-practices.aspx

于 2013-09-23T14:12:47.600 回答
4

(i)您可以为服务创建一个实例,并在需要进行方法调用时使用同一个客户端。如果您要中止或关闭连接,则每次都需要创建。

(ii)最好在每个方法中都使用try catch方法,这样可以很容易的关闭连接和识别异常。

于 2013-09-23T13:14:47.767 回答