2013-12-10 48 views
1

比方说,我有一种类型是这样的:使用多个代理生成挂钩创建代理

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

    public virtual void InterceptedByB() { } 
} 

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

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

是否有使用多个IProxyGenerationHook实现创建代理的方式?

回答

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