【问题标题】:Castle Dynamic Proxy wants to intercept Object.GetType()Castle Dynamic Proxy 想要拦截 Object.GetType()
【发布时间】:2011-10-03 18:33:52
【问题描述】:

在一个项目中,我使用 Castle Dynamic Proxy 将所有由外观运行的代码包装在 try/catch 块中(听起来很奇怪?解释 here)。这很好用,但是为了确保所有方法调用都被拦截,当我遇到非虚拟的东西时,我会抛出一个异常,使用IProxyGenerationHook 接口的NonProxyableMemberNotification 方法:

public void NonProxyableMemberNotification(Type type, MemberInfo memberInfo)
{
    throw new InvalidOperationException(string.Format(
          "Proxy failure. {0} {1} in {2} is not virtual.", 
          memberInfo.MemberType, memberInfo.Name, memberInfo.DeclaringType));
}

根据 Krzysztof Koźmic 的伟大 tutorial对象类是特殊情况,默认情况下 DynamicProxy 会忽略它们。问题是,就我而言,它们没有被忽略,从以下示例 MemberInfo 数据中可以看出:

这里有什么我错过的吗? NonProxyableMemberNotification 是否应该在 Object 方法上触发?

我正在使用 .Net 3.5、VS2010 和 Castle Core 2.5.2 版,并且我没有在我的 XmlDocumentBackend 中覆盖 Object.GetType()

【问题讨论】:

    标签: c# .net castle-dynamicproxy proxy-classes


    【解决方案1】:

    使用 NonProxyableMemberNotification 的这个实现:

    public void NonProxyableMemberNotification(Type type, System.Reflection.MemberInfo memberInfo)
        {
            if (memberInfo.DeclaringType != typeof(object))
            {
                string message = string.Format("Non-proxyable member encountered - {0} (type - {1})",
                    memberInfo.Name, type.FullName);
                throw new InvalidOperationException(message);
            }
        }
    

    【讨论】:

      【解决方案2】:

      本教程是为 DynamicProxy 版本... 2.1 IIRC 编写的。

      DynamicProxy 的这方面在最近的版本中发生了变化,因为在某些情况下 System.Object 上的方法实际上需要被拦截。 (GerHashCodeEqualsToString...)。出于这个原因,DP 在内部不会将System.Object 列入黑名单,以免被拦截,而是依赖IProxyGenerationHookAllMethodsHook 类)的默认实现来执行此操作(以便在需要时可以覆盖它)。

      因此,如果您希望对 System.Object 方法进行预过滤,只需从此类继承并使用 base 实现即可。

      我可以看到这可能会造成混淆,所以我会看看 GetHasCode 作为一种特殊情况是否可以在使用 NonProxyableMemberNotification 方法之前轻松进行预过滤。

      【讨论】:

      • 感谢您的回答,这确实解释了很多!
      猜你喜欢
      • 2018-01-30
      • 1970-01-01
      • 2012-06-01
      • 2011-10-01
      • 2011-09-30
      • 1970-01-01
      • 2018-02-05
      • 2014-08-22
      • 2013-11-08
      相关资源
      最近更新 更多