App.config外的WCF ChannelFactory配置?

我有一个使用插件系统的Windows服务。 我在插件基类中使用以下代码为每个DLL提供单独的配置(因此它将从plugin.dll.config读取):

 string dllPath = Assembly.GetCallingAssembly().Location; return ConfigurationManager.OpenExeConfiguration(dllPath); 

这些插件需要调用WCF服务,因此我new ChannelFactory("endPointName")的问题是new ChannelFactory("endPointName")只在托管应用程序的App.config中查找端点配置。

有没有办法简单地告诉ChannelFactory查看另一个配置文件或以某种方式注入我的Configuration对象?

我能想到的唯一方法是从plugin.dll.config读入的值手动创建EndPoint和Binding对象,并将它们传递给ChannelFactory重载之一。 这看起来真的像重新创建轮子,并且它可能会因为大量使用行为和绑定配置而变得非常混乱。 也许通过传递配置部分可以轻松创建EndPoint和Binding对象?

有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 factory1 = new ConfigurationChannelFactory( "endpoint1", newConfiguration, new EndpointAddress("http://localhost:8000/servicemodelsamples/service")); ICalculatorChannel client1 = factory1.CreateChannel(); 

正如Langdon所指出的那样,只需传入null即可使用配置文件中的端点地址,如下所示:

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

这在MSDN 文档中讨论。

选项2.使用代理。

如果您正在使用代码生成的代理,则可以读取配置文件并加载ServiceModelSectionGroup 。 除了简单地使用ConfigurationChannelFactory之外,还有一些工作IChannelFactory ,但至少你可以继续使用生成的代理(在引擎盖下使用ChannelFactory并为你管理IChannelFactory

Pablo Cibraro在这里展示了一个很好的例子: 从任何配置源获取WCF绑定和行为

为每个插件使用单独的AppDomain。 创建AppDomain时,您可以指定新的配置文件。

请参阅http://msdn.microsoft.com/en-us/library/system.appdomainsetup.configurationfile.aspx

这是我在第二个问题中找到的解决方案……有人将工作放入ServiceModelSectionGroup读取所有数据并创建ChannelFactory

http://weblogs.asp.net/cibrax/archive/2007/10/19/loading-the-wcf-configuration-from-different-files-on-the-client-side.aspx

我会使用理查德的解决方案,因为它似乎更清洁。