且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式获取我的客户端代理正在使用的绑定?

更新时间:2023-01-17 22:33:31

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

You can't (directly). There are a few things which you can get from the channel, such as the message version (channel.GetProperty<MessageVersion>()), and other values. But the binding isn't one of those. The channel is created after the binding is "deconstructed" (i.e., expanded into its binding elements, while each binding element can add one more piece to the channel stack.

但是,如果要在代理通道中具有绑定信息,则可以使用上下文通道的扩展属性之一自己添加它.下面的代码显示了一个示例.

If you want to have the binding information in the proxy channel, however, you can add it yourself, using one of the extension properties of the context channel. The code below shows one example of that.

public class ***_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();
    }
}