AOP or developers writing custom attributes -- pls check this

  • Thread starter Thread starter Whidbey Wave
  • Start date Start date
W

Whidbey Wave

A classic case of writing to a log file each time a particular method
is called for rudimentary performance statistics. Ordinarily the code
below satisfy the requirements:

//Considering EventLogManager to be singleton class defined in system.
public class Foo
{
public void bar()
{
EventLogManager.WriteEntry("Bar method begin; writing Stack
trace");
Debug.WriteLine(Environment.StackTrace.ToString());
// do bar()
//
EventLogManager.WriteEntry("Bar method end");
}
}

I like to factor out the logging aspect at method level. To this I
created a new attribute class:

[AttributeUsage(AttributeTargets.Method)]

Class EventLogAttribute:Attribute
{
///TODO: Don't know where to write code for method begin
///and method end.
public EventLogAttribute()
{
Debug.WriteLine(Environment.StackTrace.ToString());
}
}

public class Foo
{
[EventLog()]
public void bar()
{
// do bar()
}
}

The desired functionality is that every time the method bar() is
getting executed , it should do following:
1. Before executing the code of do bar(), it should write message "bar
method begins" and then the stack trace
2. After executing the method do bar() . it should write message "bar
methods ends"

My conclusion on trial n errors:
I may require to inherit not directly from Attribute, but some other
child class of attribute.
I saw on using ObjectContext, the attribute constructor gets called
whenever the object(on which the attribute is applied) is created.
I would like to get suggestions, before i fall back to ordinary
tactics.

Have a nice day...
 
Whidbey,

There are a few caveats here. The first is that any object you want to
use this on has to derive from ContextBoundObject. This essentially "burns"
your base class, forcing you to derive from this. Once you have this, you
will have to derive your attribute from ContextAttribute.

You then have to install sinks, etc, etc, to handle when a method with
this attribute is executed. There is an excellent article on this by Dharma
Shukla, Simon Fell, and Chris Sells titled "Aspect-Oriented Programming
Enables Better Code Encapsulation and Reuse", which you can find online at
(watch for line wrap):

http://msdn.microsoft.com/msdnmag/issues/02/03/AOP/default.aspx

While this is an effective solution, I personally don't like it, as
there are way too many caveats to use it.

Hope this helps.
 
Back
Top