简体   繁体   中英

C# How do I use AOP for static methods?

I have built ac# .net 4.0 library.

all of the methods are public and static.

i want to add an aspect using an aspect programming library that does something like this:

try block
1. call method (if method throws exception)

catch block
2. log the exception and massage the exception

it is a dll (class library project)

can you please advice if there is a way to add try/catch routines in one class instead of wrapping around all methods one by one?

Because you had mentioned word static neither nor nor anything else based upon would help you, because they able to add aspects around regular method. So you have two options:

Handwritten tracing decorator

Add separate handwritten tracing decorator that will add required functionality without altering of existing code

  • Benefits
    • Simple and easy to write yourself
  • Drawbacks
    • Almost no call context . This is important for tracing, if you like to know what method actually has been called and what parameters had been passed, etc.
    • New layer of abstraction around existed code . Instead of calling your static methods, you have to call Decorator that will call your static methods inside

Example

// Decorated calls
TraceDecorator.Aspect(() => StaticLogic.SuccessfulCall());
TraceDecorator.Aspect(() => StaticLogic.ExceptionCall());
TraceDecorator.Aspect(() => StaticLogic.SuccessfulCallWithReturn(42));
TraceDecorator.Aspect(() => StaticLogic.ExceptionCallWithReturn(42));

// Decorator itself
public static class TraceDecorator
{
    public static T Aspect<T>(Func<T> func)
    {
        try
        {
            return func();
        }
        catch(Exception ex)
        {
            LogException(ex);

            return default(T);
        }    
    }

    public static void Aspect(Action func)
    {
        try
        {
            func();
        }
        catch(Exception ex)
        {
            LogException(ex);
        }    
    }

    private static void LogException(Exception ex)
    {
        Console.WriteLine("Traced by TraceDecorator: {0}", ex);
    }
}

Full sample available here

PostSharp

Take a look at Non-Invasive Tracing & Logging with

  • Benefits
    • Broadcast your aspect without altering existing code or adding attributes by yourself, whatever you found suitable
    • Separation of concerns : tracing/logging are separated from your logic
    • and alot more …
  • Drawbacks
    • Nothing come for free. But there is a free PostSharp edition available with limited functionality
    • Sometimes integration with other tools because of post-compilation

See NConcern .NET AOP Framework , an open source project.

Example

Your static class

static public class Calculator
{
    static public int Add(int a, int b)
    {
        return a + b;
    }
}

Logger

static public class Logger
{
    static public void Log(MethodInfo method, object[] arguments, Exception exception)
    {
        Console.WriteLine("{0}({1}) exception = {2}", method.Name, string.Join(", ", arguments), exception.Message);
    }
}

Aspect : log on exception

public class Logging : IAspect
{
    public IEnumerable<IAdvice> Advise(MethodInfo method)
    {
        yield return Advice.Basic.After.Throwing((instance, arguments, exception) => 
        {
            Logger.Log(method, arguments, exception);
        });
    }
}

Joinpoint : methods of Calculator

var calculatorMethods = new Func<MethodInfo, bool>(method => method.ReflectedType == typeof(Calculator));

Activate the logging aspect for joinpoint

Aspect.Weave<Logging>(calculatorMethods);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM