views:

55

answers:

1

Hey

I have a class that handles all the interaction in my application with my WCF service and it seems that MSDN say that the use of Using)_ statement with WCF is bad - I can see why this is bad and agree with it (http://msdn.microsoft.com/en-us/library/aa355056.aspx)

my problem is that their suggested method of implementation will mean that i have 10 methods [as 10 public methods in my service] that will have the same structure code and this of course does not follow the DRY principal - the code looks similar to the following:

try
{
    results = _client.MethodCall(input parameteres);
    _client.Close();
}
catch (CommunicationException)
{
    if (_client != null && _client.State != CommunicationState.Closed)
    {
        _client.Abort();
    }
}
catch (TimeoutException)
{
    if (_client != null && _client.State != CommunicationState.Closed)
    {
        _client.Abort();
    }
}
catch (Exception ex)
{
    if (_client != null && _client.State != CommunicationState.Closed)
    {
        _client.Abort();
    }
    throw;
}

This doesn't have any logging yet but of course when I do come to start logging it then I will have to add the logging work in almost 10 different places

does anyone have any tips on how I can be a bit more resourceful here in reusing code

thanks

paul

+4  A: 

I would use some general-purpose, configurable exception handling component that allows basic exception handling processing like logging, re-throwing etc. to be decoupled from the actual place of handling. One example of such a component is Microsoft's Exception Handling Application Block.

Then you could end up with a code like this:

try
{
    results = _client.MethodCall(input parameteres);
    _client.Close();
}
catch (Exception ex)
{
    _client.CloseIfNeeded();
    if (!ex.Handle("Wcf.Policy")) throw;
}

where CloseIfNeeded denotes a custom extension method encapsulating the WCF channel closing logic, and the Handle exception method calls the exception handling mechanism, passing in a name of the exception policy that shall be applied on this place.

In most cases, you can reduce exception handling logic to a decent one or two lines of code, giving you several benefits:

  • instant configurability of exception handling behavior (policies)
  • extensibility with custom exception handlers bound to specific types of exceptions and exception policies
  • better manageability and readability of code
Ondrej Tucny
I think the solution that you have suggested is very good. the use of extension methods will make this fantastically useful - if I extended System.ServiceModel.ClientBase with the CloseIfNeeded() do you think it would be a good or a bad move?
PaulStack
What about implementing it for `System.ServiceModel.ICommunicationObject`? That would be more in-line with the architectural intent of this interface which provides the primitives for communication state management.
Ondrej Tucny
ill give that a go - thanks :)
PaulStack