Using Castle.DynamicProxy, what is the best way to create a proxy from an existing class instance?
// 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...
Here's the Person class:
public class Person
{
public virtual string Name { get; set; }
}
Here's the interceptor class:
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";
}
}
}
If your Person class has only non-virtual properties the proxy can't access them. Try to make the properties virtual.
http://kozmic.net/2009/02/23/castle-dynamic-proxy-tutorial-part-vi-handling-non-virtual-methods/