使用多个代理生成挂钩来创建代理

时间:2013-12-10 19:21:00

标签: .net castle castle-dynamicproxy

假设我有这样的类型:

public class Foo
{
    public virtual void InterceptedByA() { }

    public virtual void InterceptedByB() { }
}

我有两个名为InterceptorAInterceptorB.的选择器我想使用多个IProxyGenerationHook实现来确保它们只拦截自己的方法。 ProxyGenerator类接受一个拦截器数组,但我只能在IProxyGenerationHook构造函数中使用单个ProxyGenerationOptions实例:

var options = new ProxyGenerationOptions(new ProxyGenerationHookForA());

有没有办法使用多个IProxyGenerationHook实现来创建代理?

1 个答案:

答案 0 :(得分:1)

IProxyGenerationHook仅在代理时使用一次代理对象。如果您希望对方法使用哪种拦截器进行细粒度控制,则应使用IInterceptorSelector

这是一个(非常愚蠢的)示例,可以帮助您了解如何使用IInterceptorSelector来匹配调用的方法。当然,您不会依赖方法名称来匹配选择器,但这仍然是一个练习

internal class Program
{
    private static void Main(string[] args)
    {
        var pg = new ProxyGenerator();

        var options = new ProxyGenerationOptions();
        options.Selector = new Selector();
        var test = pg.CreateClassProxy<Foo>(options, new InterceptorA(), new InterceptorB());

        test.InterceptedByA();
        test.InterceptedByB();
    }
}

public class Foo
{
    public virtual void InterceptedByA() { Console.WriteLine("A"); }
    public virtual void InterceptedByB() { Console.WriteLine("B"); }
}


public class Selector : IInterceptorSelector
{
    public IInterceptor[] SelectInterceptors(Type type, System.Reflection.MethodInfo method, IInterceptor[] interceptors)
    {
        return interceptors.Where(s => s.GetType().Name.Replace("or", "edBy") == method.Name).ToArray();
    }
}

public class InterceptorA : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("InterceptorA");
        invocation.Proceed();
    }
}
public class InterceptorB : IInterceptor
{
    public void Intercept(IInvocation invocation)
    {
        Console.WriteLine("InterceptorB");
        invocation.Proceed();
    }
}