2

我在数据库中有客户端端点,而不是在 web.config 中。我正在使用具有多个构造函数的 ClientBase,我可以在其中传递绑定、地址等,并且可以调用客户端 wcf 服务。我在 web.config 中定义了绑定配置和行为配置。我可以在使用 ClientBase 时传递这些名称。但是我没有找到该类的任何属性或构造函数,我可以在其中传递已在 web.config 中定义的 EndpointBehavior 名称。我可以看到我可以添加 IEndpointBehavior 实例,但我不想使用它,而是更喜欢只传递在 web.config 中定义的端点行为名称。

任何帮助,将不胜感激。

谢谢。

4

1 回答 1

3

我认为没有一种方法可以让您只使用行为的名称。作为一个workaroung,您有一些方法可以从配置中加载设置,创建 IEndpointBehaviours 并将它们添加到服务端点。

using System.Configuration;
using System.ServiceModel.Configuration;

    public static void ApplyEndpointBehavior(ServiceEndpoint serviceEndpoint, string behaviorName)
    {
        EndpointBehaviorElement endpointBehaviorElement = GetEndpointBehaviorElement(behaviorName);
        if (endpointBehaviorElement == null) return;

        List<IEndpointBehavior> list = CreateBehaviors<IEndpointBehavior>(endpointBehaviorElement);

        foreach (IEndpointBehavior behavior in list)
        {
            Type behaviorType = behavior.GetType();
            if (serviceEndpoint.Behaviors.Contains(behaviorType))
            {
                serviceEndpoint.Behaviors.Remove(behaviorType);
            }
            serviceEndpoint.Behaviors.Add(behavior);
        }
    }

    public static EndpointBehaviorElement GetEndpointBehaviorElement(string behaviorName)
    {
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ServiceModelSectionGroup sectionGroup = ServiceModelSectionGroup.GetSectionGroup(config);
        if (sectionGroup == null || !sectionGroup.Behaviors.EndpointBehaviors.ContainsKey(behaviorName))
            return null;

        return sectionGroup.Behaviors.EndpointBehaviors[behaviorName];
    }

    public static List<T> CreateBehaviors<T>(EndpointBehaviorElement behaviorElement) where T : class
    {
        List<T> list = new List<T>();
        foreach (BehaviorExtensionElement behaviorSection in behaviorElement)
        {
            MethodInfo info = behaviorSection.GetType().GetMethod("CreateBehavior", BindingFlags.NonPublic | BindingFlags.Instance);
            T behavior = info.Invoke(behaviorSection, null) as T;
            if (behavior != null)
            {
                list.Add(behavior);
            }
        }
        return list;
    }

请注意,虽然它使用受保护的方法来实例化行为,但它有点 hacky。

于 2014-07-16T17:03:57.333 回答