c# - App.config 之外的 WCF ChannelFactory 配置?

标签 c# wcf wcf-configuration

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

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

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

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

我能想到的解决这个问题的唯一方法是根据从 plugin.dll.config 读取的值手动创建 EndPoint 和 Binding 对象。并将它们传递给 ChannelFactory<> 之一过载。不过,这看起来确实像是在重新创建轮子,而且对于大量使用行为和绑定(bind)配置的端点来说,它可能会变得非常困惑。 也许有一种方法可以通过向其传递配置部分来轻松创建 EndPoint 和 Binding 对象?

最佳答案

有 2 个选项。

选项 1. 使用 channel 。

如果您直接使用 channel ,.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 为您服务。

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

关于c# - App.config 之外的 WCF ChannelFactory 配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5045916/

相关文章:

c# - 如果派生类的 "reference"超出范围但基类引用保留,派生对象是否会发生变化?

c# - 在哪里生成 SignInManager IdentityUser .cshtml 文件

c# - 像 Smarty 这样的模板语言可用于 dotnet

.net - 是否可以同时调试 Silverlight 和 WCF 项目?

asp.net - 如何让服务从 global.asax 启动而无需调用它?

.net - 客户端 app.config 中的 wsHttpBinding 更改为 basicHttpBinding

c# - 检测给定字符串的地址类型

wcf - Widdle服务的POST方法在Fiddler中失败

c# - 如何将 wcf 服务添加到现有类库

WCF 客户端配置 : how can I check if endpoint is in config file,,如果不是,则回退到代码?