我正在开发一个大型系统,我必须使用WCF来访问Web服务。我的测试代码工作正常,现在我需要将我的WCF客户端代码集成到更大的系统中。我无法添加到现有的“app.config”文件中,并希望指定一个单独的.config文件供我的客户端代码使用。
我最好能做到这一点吗?
谢谢!
答案 0 :(得分:8)
有两种选择。
选项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();
正如Langdon所指出的那样,只需传入null即可使用配置文件中的端点地址,如下所示:
var factory1 = new ConfigurationChannelFactory<ICalculatorChannel>(
"endpoint1",
newConfiguration,
null);
ICalculatorChannel client1 = factory1.CreateChannel();
MSDN documentation中讨论了这一点。
选项2.使用代理。
如果您正在使用代码生成的代理,则可以阅读配置文件并加载ServiceModelSectionGroup。与简单地使用ConfigurationChannelFactory
相比,还有一些工作要做,但至少你可以继续使用生成的代理(在幕后使用ChannelFactory
并为你管理IChannelFactory
。 / p>
Pablo Cibraro在这里展示了一个很好的例子:Getting WCF Bindings and Behaviors from any config source
答案 1 :(得分:4)
你不能随心所欲 - 你可以靠近,但不能完全做到。
您可以做的是将此部分添加到主应用程序的配置文件中:
<system.serviceModel>
<bindings configSource="bindings.config" />
<behaviors configSource="behaviors.config" />
<client configSource="client.config" />
<services configSource="services.config" />
.....
</system.serviceModel>
因此对于<system.serviceModel>
中的每个部分,您可以使用configSource=
属性指定外部配置文件(并且不要让Visual Studio的红色波浪线混淆它 - 是的,它是工作!)。
您可以针对任何配置部分执行此操作 - 但遗憾的是,对于整个部分组(<system.serviceModel>
),无法执行此操作。
马克
答案 2 :(得分:1)
遗憾的是,WCF没有内置支持。您必须自己创建自己的ChannelFactory子类并加载/解析配置文件。在MSDN论坛上查看this post以获取更多实施细节。
答案 3 :(得分:0)
或者,您可以通过简单易行的方式实现 - 并实现自定义配置文件,如本文所示,它使用DataSet / DataTable模型来存储/检索您的配置(包括工作代码):
答案 4 :(得分:0)
因此marc_s DOES 提到的选项有效。忽略Visual Studio警告它无法识别绑定和所有其他位置的configSource属性。