在我们的项目中,我们使用以下代码进行WCF调用. // In generated Proxy we have..public static ICustomer Customer{ get { ChannelFactoryICustomer factory = new ChannelFactoryICustomer("Customer"); factory.Endpoint.Behaviors.Add(
// 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;
}
}
我们有Service Proxy类,它有类似的方法
public static Datatable GetCustomerDetails(int id)
{
return Services.Customer.GetCustomerDetails(id);
}
public static void .SaveCustomerDetails (int id)
{
Services.Customer.SaveCustomerDetails(id) ;
}
等…我们用来打电话.
最近我们发现我们需要“关闭”wcf连接,我们正试图找出去做而不要求我们的开发人员改变太多的代码.
请向我们提供一些有助于我们实现这一目标的建议
对于这种情况,公认的“最佳做法”将是这样的:// 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();
}
通常情况下,由于频道也实现了“IDisposable”,你可能只想把它放在一个
using(ICustomer channel = CreateCustomerChannel())
{
// use it
}
阻止 – 不幸的是,这可能会爆炸,因为很有可能在你的频道上试图调用.Close()时,你会得到另一个异常(在这种情况下会被处理).
我们的主持人Marc Gravell在这个主题上有一个有趣的blog post (don’t(don’t(use using)),有一个优雅的问题解决方案.
渣
