【问题标题】:Castle Dynamic Proxy not working?城堡动态代理不工作?
【发布时间】:2018-03-14 01:59:40
【问题描述】:

我有以下课程:

public class MyTest
{
    public void Test()
    {

    }
}

我创建了以下拦截器:

public class MyInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        invocation.Proceed();
    }
}

在我的代码中,我这样做了:

        ProxyGenerator g = new ProxyGenerator();

        g.CreateClassProxy<MyTest>(new MyInterceptor());

        MyTest t = new MyTest();
        t.Test();

不应该在调试器中使用 Intercept 方法吗?它不是。我错过了什么吗?

编辑:这是特定于 Castle DynamicProxy。

【问题讨论】:

标签: c# .net castle-dynamicproxy


【解决方案1】:

您必须将public void Test() 设置为public virtual void Test(),以便Castle DynamicProxy 可以拦截该方法。

动态代理是一种从类或 其中的接口一般是一个模型。该子类覆盖每个 它可以的方法(使您的方法虚拟以允许这样做)。

有关 Castle Dynamic Proxy 的更多文档:

https://richardwilburn.wordpress.com/2009/12/17/using-castles-dynamic-proxy/

http://putridparrot.com/blog/dynamic-proxies-with-castle-dynamicproxy/

【讨论】:

    【解决方案2】:

    CreateClassProxy 创建所谓的基于继承的代理。基于继承的代理是通过继承基类创建的。代理拦截对类的虚拟成员的调用并将它们转发到基本实现。因此只能截取类的虚拟成员。在您的示例中,您应该将Test 方法标记为virtual。见here

    public class MyTest
    {
        public virtual void Test()
        {
            Console.WriteLine("Hi");
        }
    }
    
    public class MyInterceptor : IInterceptor
    {
        public void Intercept(IInvocation invocation)
        {
            Console.WriteLine("Was here");
            invocation.Proceed();
        }
    }
    
    void Main()
    {
        ProxyGenerator g = new ProxyGenerator();
        var t = g.CreateClassProxy<MyTest>(new MyInterceptor());
        t.Test();
    }
    

    【讨论】:

    猜你喜欢
    • 2010-11-28
    • 2010-12-22
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    相关资源
    最近更新 更多