gpt4 book ai didi

.net - WCF:如何从配置中获取 Binding 对象

转载 作者:行者123 更新时间:2023-12-02 02:19:38 27 4
gpt4 key购买 nike

我想从 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

此方法为您提供配置的绑定(bind)部分。

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;
}

关于.net - WCF:如何从配置中获取 Binding 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/355576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com