【问题标题】:Selectively intercepting methods using autofac and dynamicproxy2使用 autofac 和 dynamicproxy2 选择性拦截方法
【发布时间】:2011-02-09 10:00:11
【问题描述】:

我目前正在使用 Autofac-1.4.5.676、autofac contrib 和城堡 DynamicProxy2 进行一些试验。目标是创建一个粗粒度分析器,可以拦截对特定接口的特定方法的调用。

问题:除了选择性部分之外,我的一切都完美无缺。我可能是错的,但我认为我需要将我的拦截器与 IProxyGenerationHook 实现结合起来,但我不知道该怎么做。

我的代码如下所示:

要截取&profile的接口(注意我只关心profile Update()方法)

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 方法。

现在,我如何扩展它以排除除 Update() 之外的所有方法?正如我所说,我不明白我的意思是如何通知容器“对于 ProfileInterceptor,使用 IProxyHookGenerator 的这个实现”。

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

【问题讨论】:

    标签: c# autofac castle-dynamicproxy


    【解决方案1】:

    在生成拦截器时,必须将 IProxyGenerationHook 实例传递给 CreateInterfaceProxyWithTarget 调用。有关更多详细信息,请参阅this tutorial

    目前似乎没有一种方法可以在不更改 Autofac.DynamicProxy2 集成模块的情况下提供此类挂钩。可能是对InterceptedBy 扩展的一个很好的补充。

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

    【讨论】:

    • 谢谢你的回答,彼得。由于这是用于代码分析,我希望它尽可能轻,所以我想我必须检查在拦截器内进行检查的性能并检查它的灵活性等。
    • 如果您愿意,您可以获取 AutofacContrib.DynamicProxy2 源并手动添加挂钩。这样,您至少可以在拦截器中使用钩子与过滤进行一些比较。
    • 我知道这是一个老问题,但是对于那些正在阅读这篇文章的人来说,使用更新版本的 DynamicProxy2,现在可以使用.EnableClassInterceptors(new ProxyGenerationOptions(hook)) 来指定挂钩
    • 感谢@CyrilDurand 的提醒
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2011-06-16
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      相关资源
      最近更新 更多