8

我正在开发一个大型系统,为此我必须使用 WCF 来访问 Web 服务。我的测试代码工作正常,现在我需要将我的 WCF 客户端代码集成到更大的系统中。我无法添加到现有的“app.config”文件中,并且想指定一个单独的 .config 文件供我的客户端代码使用。

我怎样才能最好地做到这一点?

谢谢!

4

5 回答 5

11

There are 2 options.

Option 1. Working with channels.

If you are working with channels directly, .NET 4.0 and .NET 4.5 has the ConfigurationChannelFactory. The example on MSDN looks like this:

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();

As pointed out by Langdon, you can use the endpoint address from the configuration file by simply passing in null, like this:

var factory1 = new ConfigurationChannelFactory<ICalculatorChannel>(
        "endpoint1", 
        newConfiguration, 
        null);
ICalculatorChannel client1 = factory1.CreateChannel();

This is discussed in the MSDN documentation.

Option 2. Working with proxies.

If you're working with code-generated proxies, you can read the config file and load a ServiceModelSectionGroup. There is a bit more work involved than simply using the ConfigurationChannelFactory but at least you can continue using the generated proxy (that under the hood uses a ChannelFactory and manages the IChannelFactory for you.

Pablo Cibraro shows a nice example of this here: Getting WCF Bindings and Behaviors from any config source

于 2013-04-19T20:25:46.383 回答
5

你不能随心所欲地做到这一点——你可以接近,但不能完全做到。

您可以做的是将此部分添加到主应用程序的配置文件中:

<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>) 执行此操作。

马克

于 2009-10-21T04:52:48.160 回答
1

不幸的是,WCF 中没有对此的内置支持。您必须自己创建自己的 ChannelFactory 子类并加载/解析配置文件。在 MSDN 论坛上查看这篇文章,了解更多实现细节。

于 2009-10-21T03:59:17.220 回答
0

或者,您可以用一种简单易行的方法来实现 - 并按照本文所述实现自定义配置文件,该文件使用 DataSet / DataTable 模型来存储/检索您的配置(包括工作代码):

(.Net)关于为程序制作配置文件的建议?

于 2009-10-21T04:09:49.823 回答
0

So the option mentioned by marc_s DOES work. Ignore Visual Studio warning that it doesn't recognize the configSource property on bindings and all other places.

于 2013-02-21T01:00:54.213 回答