【问题标题】:Load different EndpointBehavior from config programmatically以编程方式从配置加载不同的 EndpointBehavior
【发布时间】:2013-09-24 03:18:13
【问题描述】:

是否可以交换 app.config 文件中定义的端点的端点行为?

基本上,我有一个带有已定义自定义绑定的端点。从代码中,我设置了 WCF 代理客户端的端点地址。我想根据端点地址使用不同的端点行为。

伪代码:

var client = new WcfClient("endpointName", new endpointAddress("https://..."));
client.Endpoint.Behaviors.Add(EndpointBehavior.CreateFromConfig("behaviorName"));

这(很容易)可能吗?我仍然希望在 app.config 中包含我的行为定义,但会根据端点的地址动态加载它们。

【问题讨论】:

    标签: c# .net wcf app-config endpointbehavior


    【解决方案1】:

    您可以通过 System.ServiceModel.Configuration 命名空间访问配置。 阅读相应部分并手动构建您的端点/行为...

    您还可以创建多个端点并按名称实例化客户端: http://msdn.microsoft.com/en-us/library/ms751515.aspx

    您也可以尝试使用配置命名空间中的 BehaviorExtensionElement 来尝试创建行为。 我在这里找到了一个例子: http://weblogs.asp.net/cibrax/archive/2010/05/11/getting-wcf-bindings-and-behaviors-from-any-config-source.aspx

    以服务器为例:如果 ServiceHost 实例已经打开,您也可以直接从中访问大部分信息

    // BaseAddress
    Console.WriteLine(serviceHost.BaseAddress);
    
    // Endpoints (non-MEX)
    foreach (ServiceEndpoint ep in serviceHost.Description.Endpoints)
    {
      if (serviceHost.BaseAddress.Any(uri => uri.Equals(ep.ListenUri) &&
          ep.Contract.ContractType != typeof(IMetadataExchange))
      {
        Console.WriteLine("ListenURI: " + ep.ListenUri);
        Console.WriteLine("  Name   : " + ep.Name);
        Console.WriteLine("  Binding: " + ep.Binding.GetType().FullName);
      }
    }
    
    // List of MEX endpoints:
    foreach (ServiceEndpoint ep in serviceHost.Description.Endpoints)
    {
      if (ep.Contract.ContractType == typeof(IMetadataExchange))
      {
        Console.WriteLine(ep.ListenUri.ToString());
      }
    }
    

    【讨论】:

    • WCF 不公开一个从命名行为部分创建端点行为的方法吗?毕竟,WCF 在最初仅从配置构造端点时也是如此(它确实公开了*Binding 的功能)。
    • 如果添加更多信息,请查看 BehaviorExtensionElement
    • 我不能创建一个类似于从配置创建绑定的新行为吗? new CustomBinding("bindingname")。为什么没有new EndpointBehavior("behaviorname")?我不想修改代码中的行为,我想从配置中加载不同的行为。通过 ConfigurationManager 读取配置值来手动构建它对我来说似乎不合适(我担心生成的行为可能与 WCF 生成的行为略有不同,并且会引入难以追踪的错误)
    【解决方案2】:

    在运行时设置端点:

    yourProxy.ChannelFactory.Endpoint.Address = New ServiceModel.EndpointAddress("someSvcURL")

    【讨论】:

    • 不,我不想设置端点地址,我想从配置文件中按名称创建一个 EndpointBehavior 对象。
    猜你喜欢
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 2015-05-14
    • 2012-03-08
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多