Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Best Practices for creation of WCF proxy in .NET

0.00/5 (No votes)
23 Dec 2009 1  
Introduction...

Introduction



From past few days I was doing some findings about the best ways of creating the service proxy's in WCF.

Here goes the collection of results of that exercise..

1)

In this first case, We are creating the service proxy with the help of the ChannelFactory and we are closing that factory once we are done with the exercise,but it might so happen that during close call it might throw an exception,Afterwards that proxy state becomes faulted and it may be of no use(you cant make any call on that), hence to be on the safer side, by using a bool we are cleaning the instance if at all any exception happens. How cool right?
private void ProxyCreation()
{

    ChannelFactory<OrderServiceReference.OrderService> factory = default(ChannelFactory<OrderServiceReference.OrderService>);
    bool blnClosed = false;
    try
    {
        //Instantiating...
        factory = new ChannelFactory<OrderServiceReference.OrderService>("WSHttpBinding_OrderService");
        OrderServiceReference.OrderService proxy = factory.CreateChannel();

        //Make a call by proxy
        int i = proxy.GetScore();

        //Close
        factory.Close();
        blnClosed = true;
    }
    finally
    {
        if (!blnClosed)
            factory.Abort();
    }

}


2.

In this second case, we are using the proxy generated by the svcutil through VS IDE.
using block will ensure that the proxy is Disposed,and hence the resource is getting cleanedup (You can see why is it like that in the Equivalent code section)

    using (OrderServiceReference.OrderServiceClient proxy = new WindowsFormsApplication1.OrderServiceReference.OrderServiceClient())
    {
       int i = proxy.GetScore();

    } 
 
Equivalent code after compilation - 
     OrderServiceReference.OrderServiceClient proxy = default(OrderServiceReference.OrderServiceClient);
            try
            {
                proxy = new WindowsFormsApplication1.OrderServiceReference.OrderServiceClient();
                int i = proxy.GetScore();
            }
            finally
            {
                proxy.Dispose();
            }


I hope this helps!!

Regards,
-Vinayak

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here