.net WCF:如何从配置中获取绑定对象
我想从web.config或app.config获取绑定对象 因此,该代码起作用:.net WCF:如何从配置中获取绑定对象,.net,wcf,wcf-binding,.net,Wcf,Wcf Binding,我想从web.config或app.config获取绑定对象 因此,该代码起作用: wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc"); 但我想做以下几点: Binding binding = DoSomething(); wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc"); return (B
wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc");
但我想做以下几点:
Binding binding = DoSomething();
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);
当然,我对DoSomething()方法感兴趣。一个厚颜无耻的选择可能是使用默认构造函数创建一个实例,用作模板:
Binding defaultBinding;
using(TestServiceClient client = new TestServiceClient()) {
defaultBinding = client.Endpoint.Binding;
}
然后把它收起来重新使用。有什么帮助吗?您可以从App.config/Web.config实例化一个提供绑定配置名称的绑定 使用由其配置名称指定的绑定初始化WSHttpBinding类的新实例 下面的示例显示如何初始化的新实例 带有字符串参数的WSHttpBinding类
// Set the IssuerBinding to a WSHttpBinding loaded from config
b.Security.Message.IssuerBinding = new WSHttpBinding("Issuer");
查看Mark Gabarra的博客文章,它展示了如何枚举已配置的绑定如果在运行时之前不知道绑定的类型,可以使用以下方法:
Binding binding = DoSomething();
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);
其中bindingType是绑定类型,endpointConfigName是配置文件中指定的名称
所有包含的绑定都提供了一个构造函数,该构造函数将endpointConfigurationName作为唯一参数,因此这应该适用于所有绑定。我将其用于WsHttpBinding和NetTcpBinding没有任何问题。这个答案满足了OP的要求,100%摘自Pablo M.Cibraro的这篇精彩文章。 此方法为您提供配置的绑定部分
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;
}
此方法为您提供了您迫切需要的实际绑定对象
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;
}
总比什么都没有好:)但我想从配置文件中获取绑定对象,按名称加载它。前提是您知道要使用哪种绑定,例如WSHttpBinding或NetTcpBiding。您失去了在运行时更改投标类型的灵活性。但我需要任何绑定,而不仅仅是自定义绑定(WSHttpBinding):var binding=new System.ServiceModel.Channels.CustomBinding(“BindingName”);这仅说明如何枚举已配置的绑定。关于完整的内容,请查看我的答案。这只解释了如何从抽象配置定义开始初始化绑定对象。要了解完整的信息,请查看我的答案:)