2010-04-18 118 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));