开发者

Multiple Methods to call a WCF Service

开发者 https://www.devze.com 2023-01-19 09:20 出处:网络
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

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开发者_如何学C:

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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号