App.config外的WCF ChannelFactory配置?

Lan*_*don 5 c# wcf wcf-configuration

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

string dllPath = Assembly.GetCallingAssembly().Location;
return ConfigurationManager.OpenExeConfiguration(dllPath);
Run Code Online (Sandbox Code Playgroud)

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

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

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

Phi*_*ppe 4

有 2 个选项。

选项 1. 使用渠道。

如果您直接使用通道,.NET 4.0 和 .NET 4.5 具有ConfigurationChannelFactoryMSDN上的例子是这样的:

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。比简单地使用 a 涉及更多的工作ConfigurationChannelFactory,但至少您可以继续使用生成的代理(在幕后使用 aChannelFactoryIChannelFactory为您管理 a )。

Pablo Cibraro 在这里展示了一个很好的示例:Getting WCF Bindings and Behaviours from any config source

  • 起初我很失望,因为该构造函数要求您定义一个 EndpointAddress,端点已经定义了该端点地址,然后我意识到您可以发送“null”,它将使用配置的地址。感谢您发帖! (2认同)