Question

I am trying to implement AOP in a existing application with the help of postsharp

The methods in the existing application will be making a particular call on the entry and exit

class Test
{
Method1()
{
Log.Start()
//code
Log.Stop()
}

Method2
{
Log.Start()
//code
Log.Stop()
}
}

Now If I declare a aspect for this say LogAspect containing

  public override void OnEntry(MethodExecutionArgs args) 
    {
       Log.Start();
     }
     public override void OnExit(MethodExecutionArgs args) 
    {
       Log.Stop();
     }

Now I want to use this aspect for the test class

so I do this.

[LogAspect()]
class Test
{
method1()
{
}

method2()
{
}
}

Now LogAspect will be applied to all methods of test.

But Log.Start() ,Log.Stop() is already present in method1 and method2 so they get executed twice. Is there any way the LogAspect can suppress Log.Start() and Log.Stop() in method1 and method2 and execute its own functionality alone on entry and exit. Is this possible in Postsharp if not any other solution as I am new into AOP? The core point here is minimal change required to change the existing application to aspects.

Was it helpful?

Solution

Currently PostSharp itself cannot modify your code to remove the calls to your existing Log.Start() and Log.Stop() methods.

I may suggest an easy solution to apply refactoring and modify your existing logging methods, so that they do not perform logging anymore (maybe based on a condition). And inside your aspect call other new logging methods, that will perform actual logging.

public override void OnEntry(MethodExecutionArgs args) 
{
    Log.NewStart();
}

public override void OnExit(MethodExecutionArgs args) 
{
    Log.NewStop();
}

If you want a more advanced solution, then in your old logging methods' condition you could check whether the LogAspect has been applied to the current method and skip logging only in that case. But this will be quite difficult to implement and probably won't pay off with your requirement of minimal effort to add AOP.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top