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()方法感兴趣.
这个答案满足了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)
如果在运行时之前不知道绑定的类型,则可以使用以下命令:
return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);
Run Code Online (Sandbox Code Playgroud)
其中绑定类型的bindingType和endpointConfigName是配置文件中指定的名称.
所有包含的绑定都提供了一个构造函数,它将endpointConfigurationName作为唯一参数,因此这应该适用于所有这些参数.我已经将它用于WsHttpBinding和NetTcpBinding而没有任何问题.
一个厚脸皮的选项可能是使用默认构造函数创建一个实例,以用作模板:
Binding defaultBinding;
using(TestServiceClient client = new TestServiceClient()) {
defaultBinding = client.Endpoint.Binding;
}
Run Code Online (Sandbox Code Playgroud)
然后收起它并重新使用它.有帮助吗?
您可以实例化一个绑定,从App.config/Web.config中提供绑定配置名称.
http://msdn.microsoft.com/en-us/library/ms575163.aspx
使用由其配置名称指定的绑定初始化WSHttpBinding类的新实例.
以下示例说明如何使用字符串参数初始化WSHttpBinding类的新实例.
Run Code Online (Sandbox Code Playgroud)// Set the IssuerBinding to a WSHttpBinding loaded from config b.Security.Message.IssuerBinding = new WSHttpBinding("Issuer");
归档时间: |
|
查看次数: |
20651 次 |
最近记录: |