WCF使用匿名方法关闭连接

3 c# wcf

在我们的项目中,我们使用以下代码进行WCF调用.

// In generated Proxy we have..
public static ICustomer Customer
{
 get
  {
    ChannelFactory<ICustomer> factory = new ChannelFactory<ICustomer>("Customer");
    factory.Endpoint.Behaviors.Add((System.ServiceModel.Description.IEndpointBehavior)new ClientMessageInjector());
    ICustomer channel = factory.CreateChannel();
    return channel;
  }
}
Run Code Online (Sandbox Code Playgroud)

我们有Service Proxy类,它有类似的方法

public static Datatable GetCustomerDetails(int id)
{
  return Services.Customer.GetCustomerDetails(id);
} 

public static void .SaveCustomerDetails (int id)
{
  Services.Customer.SaveCustomerDetails(id) ;
}
Run Code Online (Sandbox Code Playgroud)

等...我们用来打电话.

最近我们发现我们需要"关闭"wcf连接,我们正试图找出去做而不要求我们的开发人员改变他们的代码太多.

请向我们提供一些有助于我们实现这一目标的建议

mar*_*c_s 6

对于这种情况,公认的"最佳做法"将是这样的:

// create your client
ICustomer channel = CreateCustomerClient();

try
{
   // use it
   channel.GetCustomerDetails() ....

   (more calls)

   // close it
   channel.Close();
}
catch(CommunicationException commEx)
{
   // a CommunicationException probably indicates something went wrong 
   // when closing the channel --> abort it
   channel.Abort();
}
Run Code Online (Sandbox Code Playgroud)

通常情况下,由于频道也实现了"IDisposable",你可能只想把它放在一个

using(ICustomer channel = CreateCustomerChannel()) 
{
   // use it
}
Run Code Online (Sandbox Code Playgroud)

阻止 - 不幸的是,这可能会爆炸,因为很有可能在你的频道上试图调用.Close()时,你会得到另一个异常(在这种情况下会被处理掉).

我们的主持人马克·格拉维尔(Marc Gravell)有一篇有趣的博客文章(不要(不要(使用))关于这个主题,优雅的问题解决方案.