1

I am in the process of creating an api for database operations where I have to wrap every function call in the api with a try catch. I am basically trying to get the same functionality as decorators in python.

I read a bunch of articles and this one seemed like the best example to follow: http://ayende.com/blog/3474/logging-the-aop-way. A problem I have with it is that after resolving the container with the interface of functions that need to be wrapped, you have to make a call on the resolved container to call one of those functions.

I would like the user of my controller to be able to just make a call to my class which implements the above interface and know nothing about what I have done internally as far as the try catch business.

Is this possible? I apologize if the solution is simple, I haven't had much experience with C#. Thanks.

Tony
  • 133
  • 2
  • 11

1 Answers1

0

If you can spend a few bucks on PostSharp, here is one way to accomplish this:

[Serializable]
public class PrintAndIgnoreExceptionAttribute : OnExceptionAspect
{

    public override void OnException(MethodExecutionArgs args)
    {
        Console.WriteLine(args.Exception.Message);
        args.FlowBehavior = FlowBehavior.Return;
    }
}

Then you use [PrintAndIgnoreException] to decorate your methods which need to be covered. PostSharp is also the best performing of all AOP frameworks, because the extra code is weaved in post-compilation, so there is no run-time penalty. I don't work for them, I just use it in pretty much everything I do these days.

Darek
  • 4,687
  • 31
  • 47
  • Hmm it appears that ExceptionAspects are contained in PostSharp Express, which is free. If I am not misreading their website. – hschne Dec 26 '14 at 23:58
  • It might be, try, there is no harm ... :) – Darek Dec 27 '14 at 00:08
  • PostSharp isn't a suitable solution for my company for a number of reasons. Can you guys think of any other framework or way to code what I am trying achieve? – Tony Dec 27 '14 at 04:15
  • 1
    Sorry to hear that. You know you don't need to redistribute PostSharp server to your clients or even the build server right? Anyhow, here are alternatives: http://www.postsharp.net/alternatives – Darek Dec 27 '14 at 22:28