0

Possible Duplicate:
WCF wrap proxy client

I have many web methods in services in my project that use client application.

I don't want write code something like this:

 using(ServiceClient sc = new ServiceClient())
    {
         //Invoke service methods        
         sc.Method1();
    }

Instead of, I want to write: ServiceClient.Method1(); (for example) - in this case all common operation which referred to the proxy (initialization, invoking method, disposing, exception processing) will be inside ServiceClient. Of course, i can wrap any of my web method with similar code or use reflection for retrieving method by name, but maybe any other ways are exist?

Community
  • 1
  • 1
Yury
  • 1
  • 2

2 Answers2

1

How about a static method like this:

public static TResult Execute<TResult>(Func<ServiceClient, TResult> proxy)
{
    using (var client = new ServiceClient())
    {
        return proxy(client);
    }
}

and then:

string result1 = Execute(proxy => proxy.Method1());
int result2 = Execute(proxy => proxy.Method2("some param", 123));
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Btw. this kind of disposing proxy should not be used: http://weblogs.asp.net/cibrax/archive/2009/06/26/disposing-a-wcf-proxy.aspx – Ladislav Mrnka Apr 29 '11 at 11:49
  • @Ladislav Mrnka, good point. The code could be easily adapted to use this instead of the `using` statement to simply dispose the channel. – Darin Dimitrov Apr 29 '11 at 11:54
0

If you want to, you could write a Singleton implementation that wraps all the client operations and internally maintains an initialized client.

You then expose the methods you want as static members of the singleton class. This has the added benefit of speeding the service communication since most of the overload is the creation of the proxy (contract load, binding initialization and client setup).

Sergio Vicente
  • 980
  • 1
  • 10
  • 18