views:

33

answers:

2

Hi all,

Is there anyway to intercept method call of a class so you can do AOP?

e.g.

I want the Teacher.Talk() performs differently in two scenarios:

class School
{
    [Fun]
    public void Picnic {
        Teacher t = new Teacher();
        t.Talk();
    }

    public void Seminar{
        Teacher t = new Teacher();
        t.Talk();
    }
}

In above code, the function Picnic is decorated by Fun attribute, so the Talk function of the teacher is much more interesting than the one in Seminar function which is not decorated by the attribute.

I've checked Castle.DynamicProxy, but it uses proxy class and need some code modification. That doesn't help to solve my problem because I want to use the attribute to do the configuration, so that when the decision changes, very few code modifications will be needed.

Thanks a lot in advance!

+1  A: 

After researching the same problem a few months ago, the only decent solution I found was to use PostSharp. http://www.sharpcrafters.com/

Even that isn't ideal because it disables Edit/Continue in classes using attributes (give or take).

AndrewS
+1  A: 

There are two basic approaches: creating a subclass proxy or mangling the code aka "compile-time weaving" to enter the hooks into the compiled assembly.

Subclassing only lets you intercept virtual methods and constructors while compile-time weaving can enter hooks anywhere to intercept calls in the codebase.

SargeATM
Thanks, but does subclassing provide a solution for my problem. I need to configure the object behavior in a function's scope, not a time scope.
Roy
It only provides part of the solution. You would have to:1) Use a TeacherFactory to hide the fact that you might be sending back a proxy.2) In the proxy you would have to run up the call stack and check the methods in the stack for attributes like FunAttribute that you are interested in3) Pray that your Teacher.Talk method isn't called 1 million times in an inner loop somewhere. ;-)
SargeATM