2008-12-10 62 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; 
}