Monday, May 20, 2013

Standard WCF Proxy Usage Pattern

Using a channel factory gives less grief when you can share a contract assembly between service and client. It is also easier from a unit test point of view (abstract the construction of the channel factory into a virtual method).  Using code generated proxy code is fragile as the generated code is often out of date which may not always fail in an obvious way. Its also easy to end up with duplicate classes in different namespaces on the client when only one exists in the service.

            // Cache ChannelFactory if possible until no longer required.
            // repeatedly creating it can be expensive.
            // TODO - Don't forget to dispose this factory when you're finished with it.
            private ChannelFactory factory =  
                 new ChannelFactory<IService1>("WsHttpBinding_IService1");


            ICommunicationObject commsObject = null;
            bool success;            
                    var proxy = factory.CreateChannel();                   
                    commsObject = (ICommunicationObject) proxy;
                    var request = new GetDataRequest();
                    var result = proxy.GetDataUsingDataContract(request);
                                // Message pattern - a single request type and a
                                // response type specific for the operation. This
                                // allows independent evolution of operation types.
                    success = true;
                    return result;
            }            catch (TimeoutException ex)
                   // TODO - what to do if timeout occurs?
            catch (FaultException ex)
                   // TODO - optional - if the service has its own Fault Exceptions defined.
            catch (CommunicationException ex)
                   // TODO - Any other WCF related exceptions.
                  if (!success) proxy.Abort();


Stack Overflow - Channel Factory
Microsoft MSDN Article
Stack Overflow - Generated Client Proxy

No comments:

Post a Comment