【问题标题】:castle dynamic proxy creation城堡动态代理创建
【发布时间】:2010-11-28 20:16:56
【问题描述】:

我正在实现一个设计,我的层将位于客户端和服务器之间,无论我从服务器获得什么对象,我都会将它包装在一个透明代理中并提供给客户端,这样我就可以跟踪发生了什么变化在对象中,因此在将其保存回来时,我只会发送更改的信息。

我看了一下城堡动态代理,linfu,虽然他们可以生成代理类型,但是他们不能取现有的对象,而是把它们包装起来。

想知道是否可以使用这些框架,或者是否有任何其他框架可以实现这一点......

【问题讨论】:

    标签: c# castle-dynamicproxy linfu


    【解决方案1】:

    我们使用无状态实体,并且由于 ASP.NET GridView 的行为,我需要创建一个仅包装现有对象的代理。

    我创建了一个拦截器,它以这种方式保存目标实例:

    public class ForwardingInterceptor : IInterceptor
    {
        private object target;
    
        private Type type;
    
        public ForwardingInterceptor(Type type, object target)
        {
            this.target = target;
        }
    
        public void Intercept(IInvocation invocation)
        {
            invocation.ReturnValue = invocation.Method.Invoke(this.target, invocation.Arguments);
        }       
    }
    

    然后您可以简单地创建包装代理:

    this.proxyGenerator.CreateClassProxy(type, new ForwardingInterceptor(type, target));
    

    【讨论】:

      【解决方案2】:

      Castle Dynamic Proxy 3.x 或更高版本可以做到这一点,尽管您必须记住它只能拦截虚拟方法,因此它不是一个完美的抽象。

      【讨论】:

      • 相关方法在ProxyGenerator类上以“WithTarget”结尾,例如CreateClassProxyTypeWithTarget
      猜你喜欢
      • 2010-12-22
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      • 2011-03-28
      • 1970-01-01
      • 2012-12-18
      相关资源
      最近更新 更多