7

DuplexChannelFactoryを使用して実行時に生成されたWCFプロキシがあります。

DuplexChannelFactoryから返されたサービスインターフェイスのみを指定して、バインディング情報にアクセスするにはどうすればよいですか?

IClientChannelにキャストすることでほとんどのものを取得できますが、そこにバインディング情報が見つからないようです。私が取得できる最も近いものはエンドポイントであるIClientChannel.RemoteAddressですが、これにもバインディング情報がないようです。:-/

4

1 に答える 1

6

(直接)できません。channel.GetProperty<MessageVersion>()メッセージバージョン( )やその他の値など、チャネルから取得できるものがいくつかあります。しかし、バインディングはそれらの1つではありません。チャネルは、バインディングが「分解」された後に作成されます(つまり、バインディング要素に展開されますが、各バインディング要素はチャネルスタックにもう1つのピースを追加できます。

ただし、プロキシチャネルにバインディング情報が必要な場合は、コンテキストチャネルの拡張プロパティの1つを使用して、自分でバインド情報を追加できます。以下のコードはその一例を示しています。

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();
    }
}
于 2011-06-13T16:10:26.200 に答える