4

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";
        }
    }
}

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

7 Comments

Name is a virtual property. Question updated with Person definition.
Ok, so what does your interceptor do?
The idea is to lazy load some (virtual) properties.
Ok, but what does the interceptor really do? Can you add the implementation?
That was indeed part of the problem and it seems that I need to use CreateClassProxy iso CreateClassProxyWithTarget to keep all non virtual members in sync.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.