城堡动态代理创建

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

我查看了城堡动态代理,linfu,虽然他们可以生成代理类型,但他们不能接受现有的对象并换行。

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

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

我们使用无状态实体,并且由于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));