WCF:如何从配置中获取绑定对象

bh2*_*213 16 .net wcf wcf-binding

我想从web.config或app.config获取Binding对象.

所以,这段代码有效:

wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc");
Run Code Online (Sandbox Code Playgroud)

但我想做以下事情:

Binding binding = DoSomething();
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
Run Code Online (Sandbox Code Playgroud)

当然,我对DoSomething()方法感兴趣.

dan*_*uio 8

这个答案满足了OP的要求,100%从Pablo M. Cibraro这个惊人的帖子中提取出来.

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;
}
Run Code Online (Sandbox Code Playgroud)

此方法为您提供了您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;
}
Run Code Online (Sandbox Code Playgroud)


Yos*_*han 7

查看Mark Gabarra的这篇博客文章,它展示了如何枚举配置的绑定


Jas*_*ard 7

如果在运行时之前不知道绑定的类型,则可以使用以下命令:

return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);
Run Code Online (Sandbox Code Playgroud)

其中绑定类型的bindingType和endpointConfigName是配置文件中指定的名称.

所有包含的绑定都提供了一个构造函数,它将endpointConfigurationName作为唯一参数,因此这应该适用于所有这些参数.我已经将它用于WsHttpBinding和NetTcpBinding而没有任何问题.


Mar*_*ell 6

一个厚脸皮的选项可能是使用默认构造函数创建一个实例,以用作模板:

Binding defaultBinding;
using(TestServiceClient client = new TestServiceClient()) {
    defaultBinding = client.Endpoint.Binding;
}
Run Code Online (Sandbox Code Playgroud)

然后收起它并重新使用它.有帮助吗?


Phi*_*ppe 6

您可以实例化一个绑定,从App.config/Web.config中提供绑定配置名称.

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

使用由其配置名称指定的绑定初始化WSHttpBinding类的新实例.

以下示例说明如何使用字符串参数初始化WSHttpBinding类的新实例.

// Set the IssuerBinding to a WSHttpBinding loaded from config
b.Security.Message.IssuerBinding = new WSHttpBinding("Issuer");
Run Code Online (Sandbox Code Playgroud)

  • 只有当您知道要使用哪种绑定时,例如WSHttpBinding或NetTcpBiding.您失去了在运行时更改绑定类型的灵活性. (7认同)
  • 但我需要任何绑定,不仅仅是(WSHttpBinding) (4认同)