15

Apologies for the fairly ambiguous title but what I'm trying to achieve is probably better stated in code.

I have a WCF client. When I'm calling methods I would like to wrap each call in some error handling code. So, instead of exposing the methods directly, I've created the following helper function on the client class:

    public T HandleServiceCall<T>(Func<IApplicationService, T> serviceMethod)
    {
        try
        {
            return serviceMethod(decorator);
        }
        [...]
    }

And the client code uses it like this:

service.HandleServiceCall(channel => channel.Ping("Hello"));

And the call to Ping gets nicely wrapped in some logic that will try to handle any errors.

This works great except that I now have a requirement to know which methods are actually being called on the service. Initially , I was hoping to just inspect the Func<IApplicationService, T> using Expression trees but didn't get very far.

Finally, I settled on a Decorator pattern:

    public T HandleServiceCall<T>(Func<IApplicationService, T> serviceMethod)
    {
        var decorator = new ServiceCallDecorator(client.ServiceChannel);
        try
        {
            return serviceMethod(decorator);
        }
        [...]
        finally
        {
            if (decorator.PingWasCalled)
            {
                Console.Writeline("I know that Ping was called")
            }
        }
    }

And the Decorator itself:

    private class ServiceCallDecorator : IApplicationService
    {
        private readonly IApplicationService service;

        public ServiceCallDecorator(IApplicationService service)
        {
            this.service = service;
            this.PingWasCalled = new Nullable<bool>();
        }

        public bool? PingWasCalled
        {
            get;
            private set;
        }

        public ServiceResponse<bool> Ping(string message)
        {
            PingWasCalled = true;
            return service.Ping(message);
        }
    }

It's really clunky and quite a lot of code. Is there a more elegant way of doing this?

djskinner
  • 8,035
  • 4
  • 49
  • 72

4 Answers4

2

Have you considered using aspect oriented approach? It sounds like exactly what you need.

Wrapping exceptions and other 'meta method' functionality could be written as aspects 'orthogonal' to what your serviceMethods do.

Some general information on AOP: AOP in wikipedia

And a potential solution with a container: AOP with Windsor Castle

grzeg
  • 338
  • 1
  • 6
  • I agree, this fits well. To me it feels a little overkill. Is there a simpler, native alternative? – djskinner Apr 11 '11 at 10:43
  • a more lightweight version could be the (suggested above) PostSharp. I haven't used it though. – grzeg Apr 11 '11 at 10:50
2

You could use an Expression, then inspect the body.

Something like

public T HandleServiceCall<T>(Expression<Func<IApplicationService, T>> serviceMethod)     
{         
    try         
    {          
        var func = serviceMethod.Compile();
        string body = serviceMethod.Body.ToString();
        return func(new ConcreteAppService()); 
    }        
    catch(Exception ex)
    {
        ...     
              }
}
Richard Friend
  • 15,800
  • 1
  • 42
  • 60
  • 1
    This, combined with @Enrico's description of how to inspect the method call works out well. It also incidentally solves another issues because it prevents the client entering more than a single method call - which is a nice addition. – djskinner Apr 11 '11 at 11:29
  • My final solution is a combination of answers given by @Richard Friend and @Enrico Campidoglio, where I used Enrico's code to identify the method being called. – djskinner Apr 11 '11 at 11:52
1

Here's a quick example using an expression tree:

public T HandleServiceCall<T>(Expression<Func<T>> serviceMethod)
{
    try
    {
        return serviceMethod();
    }
    finally
    {
        var serviceMethodInfo = ((MethodCallExpression)serviceMethod.Body).Method;
        Console.WriteLine("The '{0}' service method was called", serviceMethodInfo.Name);
    }
}

Note that this example assumes that the serviceMethod expression always contains a method invocation.

Related resources:

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154
  • And only one method invocation? – djskinner Apr 11 '11 at 10:56
  • Trying to test this out but Func does not contain a definition for Body. – djskinner Apr 11 '11 at 11:03
  • 1
    You need to change the type of the argument of the `HandleServiceCall` method to `Expression>` – Enrico Campidoglio Apr 11 '11 at 11:15
  • 1
    The lambda expression you pass to the `Expression>` parameter cannot contain multiple statements or you will get a compiler error, since it cannot be converted to an expression tree ("_A lambda expression with a statement body cannot be converted to an expression tree_"). – Enrico Campidoglio Apr 11 '11 at 11:22
  • I've combined your answer with @Richard's and as you suggest, used Expression as the arguement. Your second point about multiple statements is actually beneficial to me because it restricts the client to calling only one method at a time. – djskinner Apr 11 '11 at 11:31
0

Yes, I believe your code is overcooked.

In terms of Wrapping your code for a common safe disposing of proxies, look here for a nice implementation. Using it is easy:

using (var client = new Proxy().Wrap()) {
 client.BaseObject.SomeMethod();
}

Now you also need to access method name - for that simply use Environment.StackTrace. You need to add walking up the stack in Marc Gravell's Wrap.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • This approach is slightly different to the way I have designed my code. If I were to do some heavy refactoring I would definitely consider this. – djskinner Apr 11 '11 at 11:48