2008-12-10 56 views
15

我想從web.config或app.config中獲取Binding對象。WCF:如何從配置中獲取綁定對象

因此,此代碼的工作:

wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc"); 

,但我想做到以下幾點:

Binding binding = DoSomething(); 
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc"); 

我感興趣的DoSomething的()方法,當然。

回答

6

您可以從App.config/Web.config實例化綁定,給出綁定配置名稱。

http://msdn.microsoft.com/en-us/library/ms575163.aspx

初始化的WSHttpBinding類的新實例與它的配置名稱指定綁定。

以下示例說明如何使用字符串參數初始化 WSHttpBinding類的新實例。馬克Gabarra

// Set the IssuerBinding to a WSHttpBinding loaded from config 
b.Security.Message.IssuerBinding = new WSHttpBinding("Issuer"); 
+7

僅當您知道要使用何種綁定時, WSHttpBinding或NetTcpBiding。您失去了在運行時更改綁定種類的靈活性。 – Anthony 2009-10-15 12:51:03

+4

但我需要任何綁定,不僅(WSHttpBinding) – 2012-12-26 11:12:03

+0

對於自定義綁定:var binding = new System.ServiceModel.Channels.CustomBinding(「BindingName」); – Sal 2017-01-12 16:58:46

6

一個厚臉皮的選擇可能是使用默認的構造函數創建一個實例,作爲模板使用:

Binding defaultBinding; 
using(TestServiceClient client = new TestServiceClient()) { 
    defaultBinding = client.Endpoint.Binding; 
} 

然後妥善保存該離開並重新使用它。任何幫助?

+0

比沒有好:)但我想從配置文件中獲取綁定對象,按名稱加載它。 – bh213 2008-12-10 11:17:41

7

退房this博客文章,它顯示瞭如何枚舉配置的綁定

7

如果你不知道,直到運行時綁定的類型,可以使用以下命令:

return (Binding)Activator.CreateInstance(bindingType, endpointConfigName); 

其中bindingType和endpointConfigName的bindingType是配置文件中指定的名稱。

所有包含的綁定提供了一個構造函數,該構造函數將endpointConfigurationName作爲唯一參數,因此它應該適用於所有這些參數。我已經將它用於WsHttpBinding和NetTcpBinding,沒有任何問題。

4

這個答案符合OP的要求,並且從Pablo M. Cibraro的這篇出色的文章中被100%提取出來。

http://weblogs.asp.net/cibrax/getting-wcf-bindings-and-behaviors-from-any-config-source

這種方法給你配置的結合部。

private BindingsSection GetBindingsSection(string path) 
{ 
    System.Configuration.Configuration config = 
    System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(
    new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = path }, 
     System.Configuration.ConfigurationUserLevel.None); 

    var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config); 
    return serviceModel.Bindings; 
} 

該方法爲您提供實際的Binding對象,你是如此迫切需要。

public Binding ResolveBinding(string name) 
{ 
    BindingsSection section = GetBindingsSection(path); 

    foreach (var bindingCollection in section.BindingCollections) 
    { 
    if (bindingCollection.ConfiguredBindings.Count > 0 
     && bindingCollection.ConfiguredBindings[0].Name == name) 
    { 
     var bindingElement = bindingCollection.ConfiguredBindings[0]; 
     var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType); 
     binding.Name = bindingElement.Name; 
     bindingElement.ApplyConfiguration(binding); 

     return binding; 
    } 
    } 

    return null; 
} 
相關問題