2011-06-02 80 views
0

Reading the accepted answer to this question,显然使用WCF服务的正确方法是这样的(有一些修改复制)如何干净地关闭WCF服务而不会混淆你的代码?

// create your client 
CustomerClient 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(); 
} 

但是,如果我的程序使用的服务很多次,这会搞乱我的代码很多。什么是干净的方式来做到这一点,而不会混淆我的代码?我想到了一些使用lambda表达式的想法,但到目前为止,他们并不觉得很干净。

回答

1

你引用的帖子有它引用a post by Marc Gravell它使用的扩展方法让你的WCF调用可以做成看起来像这样的答案:

using (var client = new Proxy().Wrap()) { 
    client.BaseObject.SomeMethod(); 
}