2010-08-24 109 views
1

我有以下包裝來幫助我管理WCF客戶生命週期:WCF服務包裝 - 傳遞endpointConfigurationName以服務客戶端構造

public class ServiceProxyHelper<TProxy, TChannel> : IDisposable 
     where TProxy : ClientBase<TChannel>, new() 
     where TChannel : class 
    { 
     private TProxy m_proxy; 

     public TProxy Proxy 
     { 
     get 
     { 
      if (m_proxy != null) 
      { 
       return m_proxy; 
      } 
      throw new ObjectDisposedException("ServiceProxyHelper"); 
     } 
     } 

     protected ServiceProxyHelper() 
     { 
     m_proxy = new TProxy(); 
     } 

     public void Dispose() 
     { 
      //.... 
     } 
} 

我使用下列方式:

public class AccountServiceClientWrapper : ServiceProxyHelper<AccountServiceClient, IAccountService> 
    { 
    } 

    public class Test() 
    { 
     using(AccountServiceClientWrapper wrapper = new AccountServiceClientWrapper()) 
     { 
     wrapper.Proxy.Authenticate(); 
     } 
    } 

我如何修改該代碼以便爲客戶端提供endpointConfigurationName

wrapper.Proxy.Endpoint.Name = "MyCustomEndpointName"; 

不工作。 endpointConfigurationName應該是服務客戶端構造函數的提供者,但我如何使用這個包裝來做到這一點?

問候

+0

你們是不是在運行時改變這個或者這是助手的每個實例的靜態端點名稱中刪除"new"關鍵字? – 2010-08-24 11:38:48

+0

這將爲助手實例配置一次。 – jwaliszko 2010-08-24 14:23:05

回答

1

也許你可以使用Activator.CreateInstance創建代理實例傳遞endpointConfigurationName作爲參數。例如,

protected ServiceProxyHelper(string endpointConfigurationName) 
{ 
    m_proxy = (TProxy)Activator.CreateInstance(typeof(TProxy), endpointConfigurationName); 
} 

這將是您的包裝中的附加構造函數,以允許傳遞終點配置名稱。只有在代理類型不支持這種構造函數的情況下,你將得到一個運行時異常而不是編譯時錯誤。

+0

謝謝你。 – jwaliszko 2010-08-24 14:20:27

2

我會去在ServiceProxyHelper的構造函數中指定TProxy的實例。

protected ServiceProxyHelper(TProxy proxy) 
{ 
    m_proxy = proxy; 
} 

然後,代理包裝類是這樣的:

public class AccountServiceClientWrapper : ServiceProxyHelper<AccountServiceClient, IAccountService> 
{ 
private endpointCfgName = "{endpoint_here}"; 

public AccountServiceClientWrapper(): base(new AccountServiceClient(endpointCfgName)) 
     { 
      //this.Proxy.ClientCredentials.UserName.UserName = "XYZ"; 
      //this.Proxy.ClientCredentials.UserName.Password = "XYZ"; 
     } 
} 

然後,你使用它的方式仍然是完全一樣的。

當然,你需要從TProxy定義

相關問題