城堡动态代理创建

np-*_*ard 5 c# castle-dynamicproxy linfu

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

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

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

jir*_*mat 7

我们使用无状态实体,并且由于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);
    }       
}
Run Code Online (Sandbox Code Playgroud)

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

this.proxyGenerator.CreateClassProxy(type, new ForwardingInterceptor(type, target));
Run Code Online (Sandbox Code Playgroud)


Krz*_*mic 4

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