拦截器不拦截c#,城堡动态代理

时间:2013-03-20 16:10:25

标签: .net c#-4.0 castle aop

我正在尝试学习面向方面编程的概念,我正在使用城堡项目动态代理。请参阅我编写的示例代码。

拦截器似乎没有拦截?或者我在控制台窗口中没有看到“内部拦截器,呼叫前”和“内部拦截器,呼叫后”。请在这里建议我做错了什么?

class AOP 
{
    static void Main(string[] args)
    {
        ProxyGenerator generator = new ProxyGenerator();
        actual logger = generator.CreateClassProxy<actual>(new proxyforactual());
        logger.add(3, 2);
    }
}

public class proxyforactual : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("Inside interceptor, before the call");

        invocation.Proceed();

        Console.WriteLine("Inside interceptor, after the call");
    }
}


public class actual
{
    public int add(int x, int y)
    {
        Console.WriteLine("Inside method");

        return x + y;
    }
}

2 个答案:

答案 0 :(得分:2)

我的不好,仔细查看“CreateClassProxy”方法签名后,我注意到代理只会拦截虚方法。改变了我的代码如下所示,现在工作正常。

谢谢大家。

public virtual int add(int x, int y)
    {
        Console.WriteLine("Inside method");

        return x + y;
    }

答案 1 :(得分:0)

尝试使用界面并从中派生您的类和代理。

相关问题