Question

I am trying to consume a wcf rest service via reflection if possible. Take a look at the code below:

    public static object WCFRestClient<T>(string method, string uri, params object[] args)
    {        
        object o;
        object ret;
        using (ChannelFactory<T> cf = new ChannelFactory<T>(new WebHttpBinding(), uri))
        {                
            T contract = cf.CreateChannel();
            ret = contract.GetType().GetMethod(method).Invoke(o, args);

        }
        return ret;
    }

As you see it is a generic method that takes T at run time... my trouble is, I am not sure if I can really reflect on the channel object I am creating above.... Lets say I do, then the trouble starts when I want to create an object instance... Since I can't create an object instance from an interface...

I would also be happy to hear about if there is any other way to accomplish this? But I prefer to use channel mechanism if I can.

Was it helpful?

Solution

In general, creating a ChannelFactory for every operation is expensive. You should avoid that if possible. The using pattern is also problematic for ICommunicationObject types in WCF, since Dispose() generally corresponds to Close() which is a blocking/exception-throwing call. You will want to call Close() explicitly instead and handle TimeoutException and CommunicationException.

Aside from that, your approach would work. If you use ChannelFactory<T>.CreateChannel, it will create a transparent proxy object of type T which could be called upon via reflection if you want. So you won't have to worry about creating an object from the contract interface -- WCF already does that.

In your code sample, make sure to replace the o with contract and you should get the results you expect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top