2011-06-02 25 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(); 
}