WCF 服务以及围绕客户端和打开/关闭方法的最佳实践
拥有 WCF 服务和消费者,我不太确定如何处理 Open 和 Close 方法以及客户端的生命周期。
我自己创建了客户端,扩展并实现了 ClientBase 和 IMyService。我们将其称为 MyServiceClient。
我使用它的一个地方是 MembershipProvider。所以我给了MembershipProvider一个MyClient作为成员变量。
我希望在 MembershipProvider 中实例化一次(通过 IoC 容器),然后可能在客户端的每个方法调用中进行 Open 和 Close 调用。
public bool ValidateUser(string username, string password)
{
this.Open();
bool b = Channel.ValidateUser(username, password);
this.Close();
return b;
}
这是正确的做法吗?我真的不明白调用打开/关闭时到底发生了什么以及拥有一个客户端实例如何影响服务(如果有的话)。
Having a WCF service and a Consumer I'm not really sure how to handle the Open and Close methods and the lifetime of my Client.
I created the client myself extending and implementing ClientBase and IMyService. Let's call it MyServiceClient
One place I use it for example is MembershipProvider. So I gave MembershipProvider a MyClient as member variable.
I would like to have it instanced once in the MembershipProvider (via IoC container) and then perhaps do a Open and Close call inside every method call in the client.
public bool ValidateUser(string username, string password)
{
this.Open();
bool b = Channel.ValidateUser(username, password);
this.Close();
return b;
}
Is this the right way to go about it. I don't really understand what's really happening when open/close is called and how having one instance of client affects the service (if at all).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用单个客户端(WCF 代理)实例的问题之一是,当发生故障时,代理会进入故障状态,并且无法重用或 Dispose-d,只能 Abort-ed 和创建重新。另一方面,如果您在服务端使用/需要会话,则需要跨多个调用使用相同的代理实例。
无论如何,如果您现在想使用代理并稍后担心传输、会话或故障,我建议我为 WCF 代理使用这样的包装器:
并且您可以像这样调用您的服务方法:
Replace
MyService< /code> 与您的实际客户端类型。这样,您以后就可以通过在
return method(client)
行之前或之后添加代码来更改所有服务调用的打开/关闭/重用策略、添加日志记录等。One of the problems with using a single client (WCF proxy) instance is that when a fault occurs the proxy enters a faulted state, and it cannot be reused or Dispose-d, only Abort-ed and created anew. On the other hand, if you use/require Sessions on the service side you need the same proxy instance across multiple calls.
In any case, if you would like to use proxy now and worry about transport, sessions or faults later I suggest a wrapper like this that I use for my WCF proxies:
and you call your service methods like this:
Replace
MyService
with your actual client type. This way you can later change your opening/closing/reusing strategy, add logging, etc. for all service calls by adding code before or after the linereturn method(client)
.