How can I programmatically get the binding that my client proxy uses?

I have a WCF proxy generated at runtime using DuplexChannelFactory.

How can I access the binding information set only to the service interface returned from the DuplexChannelFactory?

I can get most of the materials by going to IClientChannel, but I cannot find the binding information there. The closest I can get is IClientChannel.RemoteAddress, which is the endpoint, but it also has no binding .: - /

+6
source share
1 answer

You cannot (directly). There are several things you can get from the channel, such as the version of the message ( channel.GetProperty<MessageVersion>() ) and other values. But binding is not one of them. A channel is created after the anchor is β€œdeconstructed” (ie, expanded into its anchor elements, while each anchor element can add another part to the channel stack.

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

 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(); } } 
+6
source

Source: https://habr.com/ru/post/890419/


All Articles