从现有对象创建代理

时间:2013-12-20 12:35:51

标签: c# castle-dynamicproxy

使用Castle.DynamicProxy,从现有类实例创建代理的最佳方法是什么?

// The actual object
Person steve = new Person() { Name = "Steve" };

// Create a proxy of the object
Person fakeSteve = _proxyGenerator.CreateClassProxyWithTarget<Person>(steve, interceptor)

// fakeSteve now has steve as target, but its properties are still null...

这是Person类:

public class Person
{
    public virtual string Name { get; set; }
}

这是拦截器类:

public class PersonInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {   
        Person p = invocation.InvocationTarget as Person;

        if (invocation.Method.Name.Equals(get_Name)
        {
            LoadName(p);
        }
    }

    private void LoadName(Person p)
    {
        if (string.IsNullOrEmpty(p.Name))
        {
            p.Name = "FakeSteve";
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您的Person类只有非虚拟属性,则代理无法访问它们。尝试将属性设为虚拟。

http://kozmic.net/2009/02/23/castle-dynamic-proxy-tutorial-part-vi-handling-non-virtual-methods/