我想从web.config或app.config获取Binding对象.
所以,这段代码有效:
wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc");
但我想做以下事情:
Binding binding = DoSomething(); wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
当然,我对DoSomething()方法感兴趣.
这个答案满足了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; }
此方法为您提供了您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; }
查看Mark Gabarra的这篇博客文章,它展示了如何枚举配置的绑定
如果在运行时之前不知道绑定的类型,则可以使用以下命令:
return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);
其中绑定类型的bindingType和endpointConfigName是配置文件中指定的名称.
所有包含的绑定都提供了一个构造函数,它将endpointConfigurationName作为唯一参数,因此这应该适用于所有这些参数.我已经将它用于WsHttpBinding和NetTcpBinding而没有任何问题.
一个厚脸皮的选项可能是使用默认构造函数创建一个实例,以用作模板:
Binding defaultBinding; using(TestServiceClient client = new TestServiceClient()) { defaultBinding = client.Endpoint.Binding; }
然后收起它并重新使用它.有帮助吗?
您可以实例化一个绑定,从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");