2010-06-26 38 views
0

當非託管資源開始播放時,我有一個關於接口使用的問題。 假設我有一個Web服務並生成了WCF客戶端。服務合同看起來像這樣:如何公開實現接口並使用非託管資源的類?

[ServiceContract] 
public interface ITestService 
{ 
    [OperationContract] 
    string GetData(int value); 
} 

在客戶端我使用依賴注入並結合ITestService接口TestServiceClient(與svcutil生成)。但是,當我創建ITestService並且它確實是TestServiceClient時,它應該以正確的方式處理,但客戶端不知道它。 你如何處理這個問題?

我想過產生這樣的代理類:

class TestServiceClientProxy : ITestService 
{ 
    #region ITestService Members 

    public string GetData(int value) 
    { 
     var client = new TestServiceClient(); 
     bool success = false; 
     try 
     { 
      var result = client.GetData(value); 
      client.Close(); 
      success = true; 
      return result; 
     } 
     finally 
     { 
      if (!success) 
      { 
       client.Abort(); 
      } 
     } 
    } 

    #endregion 
} 

不過,我不認爲代碼生成是去最好的方式。我應該使用一些AOP框架還是DynamicProxy?

在此先感謝您的幫助。

+0

看看這個答案:http://stackoverflow.com/questions/3010820/dependency-injection-wcf/3011473#3011473 – 2010-06-26 15:09:09

+0

什麼是綁定一個工廠,而不是代理接口的好處?你的意思是通過使用工廠,你可以把代理放在使用塊中,對吧?我的問題是,wcf代理不應該用於使用塊:http://stackoverflow.com/questions/573872/what-is-the-best-workaround-for-the-wcf-client-using-block-issue我不能強迫所有的客戶重新編寫正確的代碼。 – empi 2010-06-26 15:22:42

+0

您始終可以使用IDisposable包裝來裝飾真正的實現,該包裝在其Dispose方法中正確關閉客戶端。這將允許您在使用塊中擁有代理接口並仍然安全地關閉它。 – 2010-06-26 15:52:07

回答

0

聲明你的接口實現了IDisposable,在具體的類中實現Dispose(),你的DI提供者會正確地處理它。如果您的DI提供商不這樣做,找一個新的。

[ServiceContract] 
public interface ITestService : IDisposable 
{ 
    [OperationContract] 
    string GetData(int value); 
} 
+0

@Josh Einstein:這不是關於服務,而是關於客戶端 – empi 2010-06-26 14:57:41

+0

@Jame Ide:將IDisposable添加到我的界面定義中,迫使我的服務的用戶記住通過DI容器釋放它。更重要的是,如果我想創建服務模擬,我需要定義完全不必要的Dispose。 – empi 2010-06-26 15:01:34

+0

@empi,我的錯誤你是正確的。我將問題解釋爲如何通過客戶端的IDisposable實現來「服務器端」的服務器端。 – Josh 2010-06-26 21:52:20

相關問題