Dot-Net
WCF:如何從配置中獲取綁定對象
我想從 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 的這篇博文,它展示瞭如何列舉配置的綁定