11

希望制作一个通过 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)来查看配置文件是否声明了一个端点?

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

4

2 回答 2

11

我想提出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

        }
于 2010-04-14T16:16:19.837 回答
8

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

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”分支视为失败案例(配置无效)。

于 2009-06-18T06:41:40.767 回答