When you write the code for your (WCF) service you’ll probably find yourself writing the same code for every method for every service. It might look a bit like this (simplified):

public List<Contact> GetContacts(SomeInput input)

{

    // log usage of the service…

    try

    {

        BusinessLayer bl = new BusinessLayer();

        return bl.GetContacts(input);

    }

    catch(Exception ex)

    {

        // log exception…

        // throw FaultException…

    }

    return null;

}

Wouldn’t it be great if you could write all of this in almost one line of code and centralize all the “non-business” related code in one place?

public List<Contact> GetContacts(SomeInput input)

{

    return ServiceFacadeExecuter.Execute<BusinessLayer, List<Contact>>(

    bl => bl.GetContacts(input));

}

This is how you do it:

public static TResult Execute<TObject, TResult>(TObject theObject, Func<TObject, TResult> function)

{           

    try

    {

        return function(theObject);

    }

    catch (Exception ex)

    {

        HandleException(ex);

    }

    return default(TResult);

}

and an overloaded method

public static TResult Execute<TObject, TResult>(Func<TObject, TResult> function)

    where TObject : new()

{

    return Execute<TObject, TResult>(new TObject(), function);

}


TObject is the type of the object that your service will call, most likely your business layer.
TResult is the return type of your business layer call.
HandleException is a method that will take care of logging the exception and throwing a FaultException.

So all the stuff you would write over and over again in your service can now be centralized in the ServiceFacadeExecuter. If in 3 months you need to change something to the exception handling of your services or change the logging you only need to do it in one place. Of course this way of working is not only limited to use in your services.

I hope this article shows you the power of functional programming and the paradigm that logic (methods, delegates, lambdas) can be passed around like data to create a new level of abstraction and simplification of your code.

In the .cs file you’ll find several overloaded methods for different situations.