2

I have client endpoints in database not in web.config. I am using ClientBase which has number of constructor where I can pass binding, address etc.. and can call client wcf service. I have binding configuration and behavior configuration defined in web.config. I can pass those name when using ClientBase. But I don't find any property or constructor of that class where I can pass EndpointBehavior name which is already defined in web.config. I can see that I can add IEndpointBehavior instance but I don't want to use that and rather prefer to pass just endpointbehavior name which is defined in web.config.

Any help would be appreciated.

Thanks.

user1186065
  • 1,847
  • 3
  • 17
  • 22

1 Answers1

4

I don't think there's a method that would allow you to use just the name of the behaviour. As a workaroung here you've got methods that can load the settings from the config, create the IEndpointBehaviours and add them to the service endpoint.

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;
    }

Note it's a bit hacky though as it uses a protected method to instantiate the behaviour.

Bartosz Wójtowicz
  • 1,321
  • 10
  • 18