Delegate.CreateDelegate exception with proxies

While playing with dynamic invocation of WCF proxies I found a strange behavior with Delegate.CreateDelegate method.

It throws exception when trying to create delegate for WCF proxy method.

The following sample code causes the ArgumentException with message “Error binding to target method.”

 

        private static void Main()
        {                 
            var proxy = new DuplexChannelFactory<IMyService>(
                new InstanceContext(new MyServiceCallback()),
                "myService").CreateChannel();
            var method = proxy.GetType().GetMethod("MyOperationWithCallback");
            Debug.Assert(method != null);
            Action<IEnumerable<MyParameter>> action = proxy.MyOperationWithCallback;
            Debug.Assert(action != null);
            var d = Delegate.CreateDelegate(typeof(Action<IEnumerable<MyParameter>>), proxy, method);
        }

exception

It’s really annoying, and looks like a bug in the BCL. My workaround, was to build LINQ expression, and compile it into delegate. It however requires .NET 3.5.