2

web.config ではなく、データベースにクライアント エンドポイントがあります。バインディング、アドレスなどを渡すことができる多数のコンストラクターを持ち、クライアント wcf サービスを呼び出すことができる ClientBase を使用しています。web.config で定義されたバインド構成と動作構成があります。ClientBase を使用するときに、これらの名前を渡すことができます。しかし、web.config で既に定義されている EndpointBehavior 名を渡すことができるそのクラスのプロパティまたはコンストラクターが見つかりません。IEndpointBehavior インスタンスを追加できることがわかりますが、それを使用したくなく、web.config で定義されている endpointbehavior 名だけを渡すことを好みます。

どんな助けでも大歓迎です。

ありがとう。

4

1 に答える 1

3

動作の名前だけを使用できる方法はないと思います。ここでの回避策として、構成から設定をロードし、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;
    }

ただし、保護されたメソッドを使用して動作をインスタンス化するため、少しハックであることに注意してください。

于 2014-07-16T17:03:57.333 に答える