【问题标题】:WCF Client Configuration: how can I check if endpoint is in config file, and fallback to code if not?WCF 客户端配置:如何检查端点是否在配置文件中,如果没有则回退到代码?
【发布时间】:2010-11-03 19:56:09
【问题描述】:

希望创建一个通过 WCF 将序列化消息对象发送回服务器的客户端。

为了方便最终开发人员(不同部门),最好让他们不需要知道如何编辑配置文件来设置客户端数据。

也就是说,端点也没有嵌入/硬编码到客户端中也很棒。

在我看来,混合方案是最容易推出的解决方案:

IF(在配置中描述)使用配置文件 ELSE 回退到硬编码端点。

我发现的是:

  1. 如果未找到配置文件定义,new Client(); 将失败。
  2. new Client(binding,endpoint); 工作

因此:

Client client;
try {
  client = new Client();
}catch {
  //Guess not defined in config file...
  //fall back to hard coded solution:
  client(binding, endpoint)
}

但是有没有办法检查(除了try/catch)来查看配置文件是否声明了一个端点?

如果在配置文件中定义,但没有正确配置,上述内容是否也会失败?区分这两种情况会很好吗?

【问题讨论】:

    标签: wcf wcf-client wcf-configuration


    【解决方案1】:

    这是读取配置文件并将数据加载到易于管理的对象中的方法:

    Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    ConfigurationSectionGroup csg = c.GetSectionGroup("system.serviceModel");
    if (csg != null)
    {
        ConfigurationSection css = csg.Sections["client"];
        if (css != null && css is ClientSection)
        {
            ClientSection cs = (ClientSection)csg.Sections["client"];
            //make all your tests about the correcteness of the endpoints here
        }
    }
    

    “cs”对象将公开一个名为“endpoints”的集合,允许您访问在配置文件中找到的所有属性。

    确保您也将“if”的“else”分支视为失败案例(配置无效)。

    【讨论】:

    • 感谢 Alex 找到解决方案。 (希望 MS 将这些方法添加到框架本身。)
    • Alex 方法的问题(对我来说)是 Silverlight 似乎没有 System.Configuration DLL ... :( 所以你不能以简单的方式读取 clientconfig。任何人对如何在 Silverlight 中执行此操作有任何想法,/无需/将内容硬连接到代码中?提前致谢!
    【解决方案2】:

    我想提出AlexDrenea 解决方案的改进版本,它只对配置部分使用特殊类型。

    Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModelGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);
            if (serviceModelGroup != null)
            {
                ClientSection clientSection = serviceModelGroup.Client;
                //make all your tests about the correcteness of the endpoints here
    
            }
    

    【讨论】:

    • +1 不错。 LINQified: if ( serviceModelGroup != null && serviceModelGroup .Client.Endpoints.Cast().Any( e => e.Contract == "Services.IContract" ) ) 使用 ( var contract = new ContractClient() ) { } 否则使用正常
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2014-02-23
    • 2014-10-06
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多