Jay*_*Jay 8 wcf configuration-files wcf-client
我正在开发一个大型系统,我必须使用WCF来访问Web服务.我的测试代码工作正常,现在我需要将我的WCF客户端代码集成到更大的系统中.我无法添加到现有的"app.config"文件中,并且希望指定一个单独的.config文件供我的客户端代码使用.
我怎样才能做到最好?
谢谢!
Phi*_*ppe 10
有2个选项.
选项1.使用渠道.
如果直接使用通道,.NET 4.0和.NET 4.5具有ConfigurationChannelFactory.MSDN上的示例如下所示:
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = "Test.config";
Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration(
fileMap,
ConfigurationUserLevel.None);
ConfigurationChannelFactory<ICalculatorChannel> factory1 =
new ConfigurationChannelFactory<ICalculatorChannel>(
"endpoint1",
newConfiguration,
new EndpointAddress("http://localhost:8000/servicemodelsamples/service"));
ICalculatorChannel client1 = factory1.CreateChannel();
Run Code Online (Sandbox Code Playgroud)
正如Langdon所指出的那样,只需传入null即可使用配置文件中的端点地址,如下所示:
var factory1 = new ConfigurationChannelFactory<ICalculatorChannel>(
"endpoint1",
newConfiguration,
null);
ICalculatorChannel client1 = factory1.CreateChannel();
Run Code Online (Sandbox Code Playgroud)
这在MSDN 文档中讨论.
选项2.使用代理.
如果您正在使用代码生成的代理,则可以读取配置文件并加载ServiceModelSectionGroup.除了简单地使用之外,还有一些工作要做,ConfigurationChannelFactory但至少你可以继续使用生成的代理(在引擎盖下使用ChannelFactory并管理IChannelFactory你.
Pablo Cibraro在这里展示了一个很好的例子:从任何配置源获取WCF绑定和行为
您无法随心所欲地做到这一点-您可以接近,但不能完全做到。
您可以做的是将此部分添加到主应用程序的配置文件中:
<system.serviceModel>
<bindings configSource="bindings.config" />
<behaviors configSource="behaviors.config" />
<client configSource="client.config" />
<services configSource="services.config" />
.....
</system.serviceModel>
Run Code Online (Sandbox Code Playgroud)
因此,对于其中的每个部分<system.serviceModel>,您都可以使用configSource=属性来指定一个外部配置文件(并且不要让Visual Studio的红色波浪线混淆它-是的,它确实起作用!)。
您可以对任何配置节执行此操作-不幸的是,无法对整个节组(<system.serviceModel>)执行此操作。
渣