2016-11-18 57 views
1

我有一個使用WCF的服務器&客戶端解決方案。客戶端會在運行時詢問關於活動服務器的URL的服務,並且可以設置我使用的ChannelFactory。然而,我仍然需要使用配置文件中的所有其他WCF設置。這是我該如何做的:WCF channelfactory中的設置來自配置文件?

var clientSection = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection; 

      var address = string.Empty; 
      for(int i = 0; i < clientSection.Endpoints.Count; i++) 
      { 
       if(clientSection.Endpoints[i].Name == endpointConfigurationName) 
       { 
        var endpointAddress = new EndpointAddress(clientSection.Endpoints[i].Address.ToString()); 
        var netHttpBinding = new NetHttpBinding(clientSection.Endpoints[i].BindingConfiguration); 
        var serviceEndpoint = new ServiceEndpoint(ContractDescription.GetContract(typeof(T)), netHttpBinding, endpointAddress); 

        var channelFactory = new ChannelFactory<T>(serviceEndpoint); 

        break; 
       } 
      } 

問題是我有2個BehaviorExtensions被一些端點使用,例如這樣。

<services> 
<endpoint binding="netHttpBinding" behaviorConfiguration="protoEndpointBehavior" address="BinaryHttpProto" bindingNamespace="http://MyApp.ServiceContracts/2007/11" contract="MyApp.ServiceContracts.IMyAppClientService" /> 
</services> 

<behaviors> 
<endpointBehaviors> 
     <behavior name="protoEndpointBehavior"> 
      <protobuf /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 

<extensions> 
     <behaviorExtensions> 
     <add name="protobuf" type="ProtoBuf.ServiceModel.ProtoBehaviorExtension, protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67" /> 
     </behaviorExtensions> 
    </extensions> 

問題是我如何從clientSection.Endpoints讀取這個?並將其設置在channelFactory上?我知道我可以手動創建則是這樣的:

serviceEndpoint.EndpointBehaviors.Add(new ProtoEndpointBehavior()); 
      serviceEndpoint.EndpointBehaviors.Add(new CustomMessageInspectorBehavior()); 

但是,那麼這將是一個硬編碼的靜態,這將適用於所有終端,我需要能夠把它從配置改變。

回答

0

我想在代碼中創建所有東西,混合的解決方案並不好,在我的情況下,我使用了很多定製的東西。

+0

恭喜。但是,仍然,你的答案只適用於索姆的例子和解釋.. –

0

您不需要自己創建ChannelFactory。只需創建一個從ClientBase<T>繼承的ClientService類。 ClientBase<T>的構造函數接受一個EndpointName並自動添加與此Endpoint關聯的行爲。 ClientBase<T>也爲您提供訪問ChannelFactory<T>的可能性,您可以根據需要打開儘可能多的頻道。唯一需要進一步處理的是爲要使用的配置中的每個EndPoint添加一個名稱。

<endpoint binding="..." name="MyEndPoint" ... /> 
+0

謝謝,但它看起來像我需要爲此ClientBase類中的每個服務方法添加代碼?像這樣:return base.Channel.MySimpleMethod(request);這是真的?我有數百個webmethods。 – Banshee

+0

是的,這是缺點和正常的方式。我們只用2種方法來解決這個問題。我們的WebService有2個方法,一個用於請求結果,另一個沒有結果。所有其他的東西都是通過請求處理的,我們只是看看給定的RequestType並調用可以處理請求的處理程序。 – Rabban

+0

對不起,請不要在此下載?數百個webmethods如何只有2個?所有需要有自己的方法名稱,請求和響應? – Banshee