2010-04-18 117 views
2

我目前正在做一些嘗試,使用Autofac-1.4.5.676,autofac contrib和castle DynamicProxy2。我們的目標是創建一個粗粒度的分析器,它可以攔截對特定接口的方法的調用特定的方法。使用autofac和dynamicproxy2選擇性攔截方法

問題:除了選擇性零件之外,我有一切工作都很完美。我可能是錯的,但我認爲我需要用IProxyGenerationHook實現與攔截器結婚,但我無法弄清楚如何做到這一點。

我的代碼看起來是這樣的:

是被截獲&異形接口(注意,我只在乎紋的更新()方法)現在

public interface ISomeSystemToMonitor 
{ 
    void Update(); // this is the one I want to profile 
    void SomeOtherMethodWeDontCareAboutProfiling(); 
} 

,當我註冊我的系統與容器,我做以下:

// Register interceptor gubbins 
builder.RegisterModule(new FlexibleInterceptionModule()); 
builder.Register<PerformanceInterceptor>(); 

// Register systems (just one in this example) 
builder.Register<AudioSystem>() 
.As<ISomeSystemToMonitor>) 
.InterceptedBy(typeof(PerformanceInterceptor)); 

All ISomeSystemToMonit或從容器中取出的實例被攔截並按需要進行配置,除了它將截取其所有方法的事實,而不僅僅是Update方法。

現在,我該如何擴展它以排除除Update()以外的所有方法?正如我所說的,我不明白我是如何通知容器的:「對於ProfileInterceptor,使用這個IProxyHookGenerator的實現」。

所有幫助表示讚賞,歡呼!另外,請注意,我現在無法升級到autofac2.x;我困在1.

回答

1

當攔截器產生時,必須將IProxyGenerationHook實例傳遞給CreateInterfaceProxyWithTarget調用。有關更多詳細信息,請參見this tutorial

目前似乎沒有提供這樣的掛鉤的方式,而無需更改Autofac.DynamicProxy2集成模塊。可能是InterceptedBy擴展的一個很好的補充。

或者,您可以構建過濾到PerformanceInterceptor。查看IInvocation,您傳遞的是調用,請檢查Method屬性以決定是否配置文件。但是這當然會比繞過代理級別的攔截效率低。

+0

謝謝你的答案,彼得。由於這是代碼分析,我想保持它儘可能輕,所以我想我將不得不檢查在攔截器內進行檢查的性能,並檢查其靈活性等。 – 2010-04-19 10:49:06

+0

如果您感覺最多它可以抓住AutofacContrib.DynamicProxy2源並手動添加鉤子。這樣,你至少可以在攔截器中使用鉤子與過濾進行比較。 – 2010-04-19 11:25:03

+0

是的,我會給它一個去:) – 2010-04-19 13:06:39

0

對於DynamicProxy2,EnableInterfaceInterceptors方法現在有一個超載,需要ProxyGenerationOptions對象。

//Define the builder 
var builder = new ContainerBuilder(); 

//Instantiate your Proxy options with a selector 
var proxyOptions = new ProxyGenerationOptions {Selector = new MyInterceptSelector()}; 

//Pass the proxy options as a parameter to the EnableInterfaceInterceptors method 
builder.RegisterType<MyRepo>() 
      .As<IMyRepo>() 
      .EnableInterfaceInterceptors(proxyOptions) 
      .InterceptedBy(typeof(IInterceptor));