使用WebChannelFactory创建后处置客户端

Bap*_*net 2 c# wcf dispose webchannelfactory

在我目前的生产代码中,根据msdn上的文档,创建客户端的方法就是这样

using (WebChannelFactory<IServiceInterface> cf
      = new WebChannelFactory<IServiceInterface>("http://service.url"))
{
    IServiceInterface client = cf.CreateChannel();
    client.CallTheMethod();
}
Run Code Online (Sandbox Code Playgroud)

鉴于我有这个界面:

public interface IServiceInterface
{
    void CallTheMethod();
}
Run Code Online (Sandbox Code Playgroud)

但是我注意到WebChannelFactory创建的对象客户端也实现了IDisposable.所以我也要处理这个对象.我没有找到任何其他方式:

using (WebChannelFactory<IServiceInterface> cf
      = new WebChannelFactory<IServiceInterface>("http://service.url"))
using(IDisposable client = (IDisposable)cf.CreateChannel())
{
    ((IServiceInterface)client).CallTheMethod();
}
Run Code Online (Sandbox Code Playgroud)

我发现这很难看.所以:

  • 我真的需要处理它吗?我的意思是,当您处理工厂时(如果工厂保留对其创建的每个对象的引用可能),它可能会被处理掉?
  • 如果是的话,你有更好的方法吗?

Ali*_*tad 5

这是一个非常复杂的问题.即使微软自己也承认,处理渠道工厂是一个糟糕的设计,多次改变,所以简短的答案是否定的,你需要使用替代品.

这是一种替代处理方法.