Search code examples
c#.netcastle-dynamicproxyproxy-classes

Castle Dynamic Proxy wants to intercept Object.GetType()


In a project, I'm using a Castle Dynamic Proxy to wrap all code run by a façade in try/catch blocks (sounds odd? Explained here). That works fine, but to make sure all method calls are intercepted, I throw an exception when I come across something non-virtual, using the NonProxyableMemberNotification method of the IProxyGenerationHook interface:

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

According to Krzysztof Koźmic's great tutorial; Object classes are spe­cial cases, and by default Dynam­icProxy will just ignore them. Problem is, in my case they are not ignored, as seen from the following sample MemberInfo data:

memberInfo QuickWatch

Is there something I've missed here? Is NonProxyableMemberNotification supposed to fire on Object methods?

I'm using .Net 3.5, VS2010 and Castle Core version 2.5.2, and I'm not overriding Object.GetType() in my XmlDocumentBackend.


Solution

  • Use this implementation of 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);
            }
        }