Add an extra interface with Castle Dynamic Proxy 2?

I would like to create a dynamic proxy for an existing type, but add an implementation of a new interface that is not yet declared in the target type. I can’t figure out how to achieve this. Any ideas?

+3
source share
2 answers

You can use overload ProxyGenerator.CreateClassProxy()with parameter additionalInterfacesToProxy. For example, if you have a class with a string name property and you need to add IEnumerable<char>to it that lists the characters of the name, you can do this as follows:

public class Foo
{
    public virtual string Name { get; protected set; }

    public Foo()
    {
        Name = "Foo";
    }
}

class FooInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        if (invocation.Method == typeof(IEnumerable<char>).GetMethod("GetEnumerator")
            || invocation.Method == typeof(IEnumerable).GetMethod("GetEnumerator"))
            invocation.ReturnValue = ((Foo)invocation.Proxy).Name.GetEnumerator();
        else
            invocation.Proceed();
    }
}


var proxy = new ProxyGenerator().CreateClassProxy(
    typeof(Foo), new[] { typeof(IEnumerable<char>) }, new FooInterceptor());

Console.WriteLine(((Foo)proxy).Name);
foreach (var c in ((IEnumerable<char>)proxy))
    Console.WriteLine(c);

Note that a property Namedoes not have to be virtual here unless you want to proxy it.

+5
source

, additionalInterfacesToProxy

+2

All Articles