开发者

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? Explai开发者_运维知识库ned 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:

Castle Dynamic Proxy wants to intercept Object.GetType()

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.


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


The tutorial was written for DynamicProxy Version... 2.1 IIRC.

That aspect of DynamicProxy has changed in more recent version as there were situations where methods on System.Object actually needed to be intercepted. (GerHashCode, Equals, ToString...). For that reason DP internally doesn't blacklist System.Object from being interceptable and instead relies on the default implementation of IProxyGenerationHook (the AllMethodsHook class) to do it (so that it can be overridden if needed).

So if you want System.Object methods to be pre-filtered just inherit from this class and use base implementation.

I can see how this can be confusing though, so I'll see if GetHasCode, being a special case can be easily pre-filtered even before hitting NonProxyableMemberNotification method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜