开发者

How to intercept method call of a class

开发者 https://www.devze.com 2023-01-10 00:28 出处:网络
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:

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 w开发者_Python百科ant 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!


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.


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消