代理接口+抽象类,仅拦截接口调用

时间:2016-10-19 22:53:32

标签: castle-dynamicproxy

我有以下结构:

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

我想创建一个代理,将MyClass作为目标,可以同时转换为AbstractClass和Interface,但是,它应该只拦截接口调用。

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

花了一些小小的东西,但多亏了this SO question,我只能拦截接口方法。

假设:

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

这个拦截器应该做你想做的事情:

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();
    }
}

我的测试代码是:

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();