2015-11-02 39 views
0

下面是我的父類如何通過解析派生類來攔截父類方法?

public class Parent 
{ 
    //This method is intercept-able using **VirtualMethodInterceptor** 
    public virtual void Test() 
    { 
    //Do something 
    } 
} 

下面是我的子類

public class Child:Parent 
{ 
// This method directly not intercept-able but it calls base.Test() where Test is an intercept-able method 
public void Demo(){ 
    base.Test(); 
} 
} 

現在我要解決使用Unity Child類,其中Demo方法將截取的實例。實際上Demo方法不能被攔截,因爲它不是虛擬的,但是這個方法在內部調用base.Test(),其中Test是可攔截的。那麼如何解決一個Child類的可攔截實例呢?

它不工作,如果我註冊子類到一個統一的容器如下面

container.RegisterType<Child>(
      new Interceptor<VirtualMethodInterceptor>(), 
      new InterceptionBehavior<Interceptor>() 
      ) 

回答

0

確保您已經完成了以下內容:

1)您加入Interception擴展這樣的:

container.AddNewExtension<Interception>(); 

2)您的攔截行爲類的WillExecute屬性返回true

3)你獲得從容器中Child實例。這可直接完成這樣的:

Child chlid = container.Resolve<Child>(); 

或通過具有Child作爲某些類的依賴,然後解析它包含使用該容器這個類的對象圖。

+0

雖然以上所有內容都已經存在於我的代碼中,但無論如何感謝您的建議。 首先,我想解決如上所述的罰款實例。現在,如果我使用子實例調用Demo()方法,那麼應該攔截Test()方法,因爲Demo()在內部調用Test()並且Test()是虛方法,所以它應該被VirtualMethodInterceptor行爲攔截 – shou

+0

我測試了你的方案,它在我的機器中工作。你能分享一個更完整的代碼嗎? –