WCF客户端配置:如何检查终结点是否在配置文件中,并在没有时回退到代码?

11

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

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

话虽如此,如果端点也没有嵌入/硬编码到客户端中,则会更加出色。

对我来说,混合场景似乎是最容易实现的解决方案:

IF(在配置中描述)USE config file ELSE fallback to hard-coded endpoint。

我的研究结果是:

  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以外,是否有任何方式可以检查配置文件中是否声明了端点?

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

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

        }

1
LINQ化:如果(serviceModelGroup!= null && serviceModelGroup.Client.Endpoints.Cast <ChannelEndpointElement>()。Any(e => e.Contract ==“Services.IContract”)) 使用(var contract = new ContractClient()) {} else use normal+1 很好。 - Ruben Bartelink

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”分支,并将它们视为失败情况(配置无效)。"

感谢Alex找到了解决方案。(希望微软能够将这些方法添加到框架本身。) - Ciel
Alex的方案对我来说存在问题,因为Silverlight似乎没有System.Configuration DLL... :( 所以你无法轻松地读取clientconfig。 有没有人有任何想法,可以在Silverlight中完成这个任务,而不需要将东西硬编码到代码中?提前感谢! - Per Lundberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接