在编程构造的端点上声明性地配置WCF行为扩展

时间:2012-04-19 16:18:41

标签: wcf app-config endpointbehavior

我有一个WCF行为扩展,我想添加到WCF客户端。但是,客户端是以编程方式构建的。端点地址可能会有所不同,但我知道类型。我可以通过编程方式或在配置文件中添加行为(首选),但我只需要在配置文件中传递一些配置。

我不想在Common behavior(machine.config)中使用它。

我可以通过编程方式添加行为

endpoint.Behaviors.Add(new MyCustomBehavior())

但我宁愿在配置中这样做,所以我也可以在那里配置扩展。

是否可以声明性地为编程构造的端点添加和配置端点行为扩展,同时只知道类型或接口,同时让客户端端点以编程方式构建?

<system.serviceModel>
  <client>
    <!-- Created programmatically -->
  </client>
<extensions>
  <behaviorExtensions>
    <add name="MyCustomBehavior" type="namespace.CustomBehaviors", MyAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </behaviorExtensions>   
</extensions>
  <behaviors>
    <endpointBehaviors>
      <behavior name="MyCustomBehavior">
        <MyCustomBehavior MyImportantBehaviorParam1="foo"  />
      </behavior>
    </endpointBehaviors>   
  </behaviors>
</system.serviceModel>

当然,我可以将配置放在另一个部分,让我的行为在那里阅读,但如果可能,我宁愿使用WCF设施。

1 个答案:

答案 0 :(得分:10)

为此,您需要为端点创建行为配置扩展。有关如何执行此操作的详细信息,请查看http://blogs.msdn.com/b/carlosfigueira/archive/2011/06/28/wcf-extensibility-behavior-configuration-extensions.aspx

更新:我现在看到你的问题。没有直接的方法可以将通过代码创建的端点添加到配置中声明的行为。但是,您仍然可以执行此操作,但是您需要使用一些反射来访问行为配置扩展的CreateBehavior方法(该方法受到保护),以实际创建端点行为以将其添加到创建的端点通过代码。下面的代码显示了如何做到这一点。

public class StackOverflow_10232385
{
    public class MyCustomBehavior : IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            Console.WriteLine("In {0}.{1}", this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            Console.WriteLine("In {0}.{1}", this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            Console.WriteLine("In {0}.{1}", this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        }

        public void Validate(ServiceEndpoint endpoint)
        {
            Console.WriteLine("In {0}.{1}", this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        }
    }

    public class MyCustomBehaviorExtension : BehaviorExtensionElement
    {
        public override Type BehaviorType
        {
            get { return typeof(MyCustomBehavior); }
        }

        protected override object CreateBehavior()
        {
            return new MyCustomBehavior();
        }
    }

    [ServiceContract]
    public interface ITest
    {
        [OperationContract]
        string Echo(string text);
    }
    public class Service : ITest
    {
        public string Echo(string text)
        {
            return text;
        }
    }

    public static void Test()
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");

        var configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ServiceModelSectionGroup smsg = configuration.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;
        EndpointBehaviorElement endpointBehaviorElement = smsg.Behaviors.EndpointBehaviors["MyCustomBehavior_10232385"];
        foreach (BehaviorExtensionElement behaviorElement in endpointBehaviorElement)
        {
            MethodInfo createBehaviorMethod = behaviorElement.GetType().GetMethod("CreateBehavior", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, Type.EmptyTypes, null);
            IEndpointBehavior behavior = createBehaviorMethod.Invoke(behaviorElement, new object[0]) as IEndpointBehavior;
            endpoint.Behaviors.Add(behavior);
        }

        host.Open();
        Console.WriteLine("Host opened");

        ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
        ITest proxy = factory.CreateChannel();
        Console.WriteLine(proxy.Echo("Hello"));

        ((IClientChannel)proxy).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

此代码的配置:

<system.serviceModel>
    <extensions>
        <behaviorExtensions>
            <add name="myCustomBehavior_10232385" type="QuickCode1.StackOverflow_10232385+MyCustomBehaviorExtension, QuickCode1"/>
        </behaviorExtensions>
    </extensions>
    <behaviors>
        <endpointBehaviors>
            <behavior name="MyCustomBehavior_10232385">
                <myCustomBehavior_10232385/>
            </behavior>
        </endpointBehaviors>
    </behaviors>
</system.serviceModel>