【问题标题】:How can I programmatically get the binding that my client proxy is using?如何以编程方式获取客户端代理正在使用的绑定?
【发布时间】:2011-06-13 15:31:29
【问题描述】:

我有一个在运行时使用 DuplexChannelFactory 生成的 WCF 代理。

如果仅给定从 DuplexChannelFactory 返回的服务接口,如何访问绑定信息?

我可以通过转换为 IClientChannel 来获得大部分内容,但我似乎无法在其中找到绑定信息。我能得到的最接近的是 IClientChannel.RemoteAddress ,它是一个端点,但它似乎也没有绑定信息。 :-/

【问题讨论】:

    标签: wcf binding endpoint


    【解决方案1】:

    你不能(直接)。您可以从频道中获取一些信息,例如消息版本 (channel.GetProperty<MessageVersion>()) 和其他值。但绑定不是其中之一。通道是在绑定被“解构”后创建的(即扩展成它的绑定元素,而每个绑定元素可以在通道堆栈中再添加一个片段。

    但是,如果您想在代理通道中拥有绑定信息,您可以使用上下文通道的扩展属性之一自行添加。下面的代码展示了一个例子。

    public class StackOverflow_6332575
    {
        [ServiceContract]
        public interface ITest
        {
            [OperationContract]
            int Add(int x, int y);
        }
        public class Service : ITest
        {
            public int Add(int x, int y)
            {
                return x + y;
            }
        }
        static Binding GetBinding()
        {
            BasicHttpBinding result = new BasicHttpBinding();
            return result;
        }
        class MyExtension : IExtension<IContextChannel>
        {
            public void Attach(IContextChannel owner)
            {
            }
    
            public void Detach(IContextChannel owner)
            {
            }
    
            public Binding Binding { get; set; }
        }
        static void CallProxy(ITest proxy)
        {
            Console.WriteLine(proxy.Add(3, 5));
            MyExtension extension = ((IClientChannel)proxy).Extensions.Find<MyExtension>();
            if (extension != null)
            {
                Console.WriteLine("Binding: {0}", extension.Binding);
            }
        }
        public static void Test()
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITest), GetBinding(), "");
            host.Open();
            Console.WriteLine("Host opened");
    
            ChannelFactory<ITest> factory = new ChannelFactory<ITest>(GetBinding(), new EndpointAddress(baseAddress));
            ITest proxy = factory.CreateChannel();
    
            ((IClientChannel)proxy).Extensions.Add(new MyExtension { Binding = factory.Endpoint.Binding });
    
            CallProxy(proxy);
    
            ((IClientChannel)proxy).Close();
            factory.Close();
    
            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2012-07-05
      • 2011-02-15
      • 1970-01-01
      • 2013-03-02
      • 2020-06-30
      • 1970-01-01
      相关资源
      最近更新 更多