當非託管資源開始播放時,我有一個關於接口使用的問題。 假設我有一個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?
在此先感謝您的幫助。
看看這個答案:http://stackoverflow.com/questions/3010820/dependency-injection-wcf/3011473#3011473 – 2010-06-26 15:09:09
什麼是綁定一個工廠,而不是代理接口的好處?你的意思是通過使用工廠,你可以把代理放在使用塊中,對吧?我的問題是,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
您始終可以使用IDisposable包裝來裝飾真正的實現,該包裝在其Dispose方法中正確關閉客戶端。這將允許您在使用塊中擁有代理接口並仍然安全地關閉它。 – 2010-06-26 15:52:07