0

I have the following structure:

abstract class AbstractClass{...}
interface Interface {...}
class MyClass : AbstractClass, Interface{...}

I want to create a proxy that would take MyClass as a target, could be cast to both - AbstractClass and Interface, however, it should only intercept Interface calls.

What's the best way to achieve that?

M T
  • 968
  • 1
  • 8
  • 24

1 Answers1

0

It took a bit of fiddling, but thanks to this SO question, I was able to intercept only interface methods.

Given:

public abstract class AbstractClass ...
public interface IBar ...
public class MyClass : AbstractClass, IBar ...

This interceptor should do what you want:

public class BarInterceptor : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        var map = invocation.TargetType.GetInterfaceMap(typeof(IBar));
        var index = Array.IndexOf(map.TargetMethods, invocation.Method);

        if (index == -1)
        {
            // not an interface method
            invocation.Proceed();
            return;
        }

        Console.WriteLine("Intercepting {0}", invocation.Method.Name);
        invocation.Proceed();
    }
}

My test code was:

var mc = new MyClass();
var gen = new ProxyGenerator();
var proxy = gen.CreateClassProxyWithTarget(typeof(MyClass), mc, new BarInterceptor());

((AbstractClass) proxy).GetString();
((AbstractClass) proxy).GetInt();
((IBar) proxy).GetItem();
Community
  • 1
  • 1
PatrickSteele
  • 14,489
  • 2
  • 51
  • 54
  • or better yet, override `ShouldInterceptMethod` http://kozmic.net/2009/01/17/castle-dynamic-proxy-tutorial-part-iii-selecting-which-methods-to/ – Krzysztof Kozmic Nov 12 '16 at 09:28