Blog Stats
  • Posts - 23
  • Articles - 0
  • Comments - 15
  • Trackbacks - 0

 

Thursday, May 26, 2011

WCF Factory Utility


At a client I work at, we have a few dozen WCF services used throughout the environment. It's become difficult to consolidate the various services so that people know when knew ones become available and to administer their connections as environments change.

To address this, we created one web project that has connection information for every service. Each service has a different factory method depending on Binding and Endpoint credentials. The bindings and endpoints are generated programmatically, rather than through the convoluted XML nodes necessary in the App.Config.

We have a few base classes BaseBinding, and BaseEndpoint:

class BaseBinding : System.ServiceModel.BasicHttpBinding
{
public BaseBinding()
{
}
}

class BaseEndpoint : System.ServiceModel.EndpointAddress
{
public BaseEndpoint(string serviceName) :
base(ConstructUri(serviceName))
{

}

private static string ConstructUri(string serviceName)
{
// Could read from config, or local resource file to determine appropriate
// addresses based on environment (prod, dev, UAT)
if (serviceName == "WEATHER")
return "http://wsf.cdyne.com/WeatherWS/Weather.asmx";
else
return "http://www.w3schools.com/webservices/tempconvert.asmx";
}
}

And also in the ServiceLibrary we have our sample classes:

public class TempuratureUtil : TempuratureService.TempConvertSoapClient
{
public TempuratureUtil() :
base(new BaseBinding(), new BaseEndpoint("Tempurature"))
{
}
}

public class WeatherUtil : WeatherService.WeatherSoapClient
{
public WeatherUtil() :
base(new BaseBinding(), new BaseEndpoint("WEATHER"))
{
}
}

Now in the application layer, I simply add a reference to the class library:

static void Main(string[] args)
{


try
{
TempuratureUtil temp = new TempuratureUtil();
string result = temp.CelsiusToFahrenheit("23");

WeatherUtil weather = new WeatherUtil();
var forecast = weather.GetCityForecastByZIP("55337");
}
catch (Exception ex)
{
string output = ex.Message;
}
}

The application is not concerned with the specifics of the WCF service, it is all determined by the class library which is being referenced.

 

 

Copyright © jkrebsbach