代码之家  ›  专栏  ›  技术社区  ›  Mark Simpson

使用autofac和dynamicproxy 2的选择性截获方法

  •  2
  • Mark Simpson  · 技术社区  · 16 年前

    我正在做一些使用autofac-1.4.5.676、autofac contrib和castle dynamicproxy 2的实验。目标是创建一个粗粒度的分析器,它可以拦截对 具体的 特定接口的方法。

    问题是:除了选择部分之外,我的一切都很完美。我可能错了,但我想我需要把截取程序与iproxygenerationhook实现结合起来,但我不知道如何做到这一点。

    我的代码如下:

    要截取并分析的接口(注意,我只关心分析 UpDead() 方法)

    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)); 
    

    从容器中提取的所有IsomeSystemToMonitor实例都将被截取并按需要进行分析,但它将截取其所有方法,而不仅仅是更新方法。

    现在,我如何扩展它以排除update()以外的所有方法?正如我所说的,我不明白我应该如何通知容器,“对于profileinterceptor,使用iproxyhookgenerator的这个实现”。

    感谢大家的帮助,干杯!另外,请注意,我现在无法升级到autofac2.x;我被1卡住了。

    2 回复  |  直到 9 年前
        1
  •  1
  •   Peter Lillevold Rene    16 年前

    IProxyGenerationHook 实例必须传递给 CreateInterfaceProxyWithTarget 生成拦截器时调用。见 this tutorial 更多细节。

    目前似乎没有办法在不更改autofac.dynamicProxy 2集成模块的情况下提供此类挂钩。可能是个不错的补充 InterceptedBy 延伸。

    或者,您可以将过滤构建到 PerformanceInterceptor . 看着 IInvocation 调用时传递,请检查 Method 属性来决定是否分析。但这当然比在代理级别绕过拦截效率低。

        2
  •  0
  •   CodeAlchemist    9 年前

    对于dynamicProxy 2, 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));