城堡windsor拦截器在另一种方法调用的方法上

时间:2015-07-07 08:02:16

标签: c# castle-windsor aop interceptor aspect

拦截

public class CachingInterceptor : IInterceptor
{

    public void Intercept(IInvocation invocation)
    {
       // code comes here.... 
    }

}

业务层

public class Business : IBusiness
{
     public void Add(string a)
        {

             var t= GetAll();             
             // code comes here.... 

        }

     [CacheAttribute]
     public string GetAll()
        {
             // code comes here.... 

        }

}

public class JustForTest
{

     public JustForTest(IBusiness business)
            {

               //if GetAll is invoked directly caching works fine.
               business.GetAll();

               //if GetAll is invoked over Add method caching doesn't work.
               business.Add();                      

            }

  }

添加方法调用GetAll方法。如果我直接调用GetAll方法,缓存工作。如果Add方法调用GetAll方法,则缓存不起作用。

感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

接口代理是通过包装代理目标对象创建的,因此无法使用接口。

您可以拦截对相同对象的调用,但仅限于类代理(假设该方法是虚拟的)。 请参阅类似question的答案。

您还可以尝试以不同方式构建代码,将需要缓存的逻辑移动到可以缓存的服务而不使用它自己的函数。

答案 1 :(得分:4)

这里的问题是该行

var t= GetAll();

内部Business。它可以更清楚地写成

var t = this.GetAll();

this不是截获/包装的实例。

尝试按照建议herehere

划分Business班级的职责
相关问题