Sunday, May 26, 2013

Creating Dynamic WCF service proxy with Generic Factory class

Problem with static proxy is that in case of any change in service we need to manually update the service reference in our project. The alternative is Dynamic proxy using .Net ClientFactory generic class. The dynamic proxy allows you to create the dynamic WCF client at runtime. This avoids dependency on precompiled proxy or configuration. Let us see how to accomplish this in following example in c#:

Scenario:

I have a web application which requires dynamic instantiation of proxy. Following are the components :


  • Calling Application 
  • ServiceHelper
  • ServiceFactory
  • Web.config file containing the service configuration information
  • Service Contract information





Project structure:












Web.Config:



















Calling Application (WebForm here):
















ServiceHelper.cs:

This class works as a layer between calling application and ServiceProxy class.




ServiceProxy class:












ProxyFactory class is a custom factory class to create proxy object of given type. It uses ChannelFactory method of System.ServiceModel.ChannelFactory to create and return the channel (proxy).

So in nutshell from UI we request desired proxy from ServiceHelper class, which then reads the endpoint name of the asked service from configuration file and then passes the endpoint name to ProxyFactory class.

ProxyFactory class then uses ChannelFactory class to create the proxy object of wcf service using endpoint name and returns back the proxy object. ProxyFactory class is designed generic in nature to return proxies.

Happy Coding!!