2013-12-10 51 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(); 
    } 
}