Castle Dynamic Proxy not intercepting method calls when invoked from within the class

后端 未结 1 636
醉酒成梦
醉酒成梦 2020-12-14 20:31

I have run into a bit of (what I think is) strange behaviour when using Castle\'s Dynamic Proxy.

With the following code:

class Program
{
    stati         


        
相关标签:
1条回答
  • 2020-12-14 20:53

    EDIT: tl;dr - I've just tried creating the proxy in a different way, as described below, and it produces the output you were after. I just had to change this:

    var c = new InterceptedClass();
    var i = new Interceptor();
    
    var cp = new ProxyGenerator().CreateClassProxyWithTarget(c, i);
    

    To this:

    var i = new Interceptor();
    var cp = new ProxyGenerator().CreateClassProxy<InterceptedClass>(i);
    

    As I understand it, the proxy generator is effectively creating a wrapper object. They're two separate objects - one is just a wrapper around the other, with interception etc in the wrapper layer.

    It's hard to see how it could change what the instance of InterceptedClass did with its own method calls:

    • DynamicProxy can't change the type of an existing object; once an object is created, its type is fixed
    • DynamicProxy can't change how existing calls to an existing object are bound

    If you want Method1 to call Method2 via the wrapper using the current proxy creation code, you'll need to tell the existing object about the wrapper, either as a field within it or as a method parameter.

    Alternatively, there may be a different way of creating the proxy to start with - one where the proxy is in some sense the target object. I suspect you may want to look at CreateClassProxy rather than CreateClassProxyWithTarget - I suspect it's the fact that you're supplying the target object which is causing you problems.

    Whether the behaviour you're seeing is "expected" or not obviously depends on your expectations - but it's certainly what I would expect, without knowing anything about Castle Dynamic Proxy :)

    0 讨论(0)
提交回复
热议问题