2010-01-21 101 views
1

接口方法我喜歡這個攔截只DynamicProxy

public interface IService 
{ 
    void InterceptedMethod(); 
} 

實現該接口,也是一個類的接口有另一種方法

public class Service : IService 
{ 
    public virtual void InterceptedMethod() 
    { 
     Console.WriteLine("InterceptedMethod"); 
    } 

    public virtual void SomeMethod() 
    { 
     Console.WriteLine("SomeMethod"); 
    } 
} 

和一個攔截

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

我只想攔截存在於IService上的Service上的方法(即我想攔截Intercepte dMethod()但不是SomeMethod()),但我不想從IProxyGenerationHook中使用ShouldInterceptMethod。

我可以這樣做,但是因爲其返回的接口,我不能叫這個的someMethod對象

var generator = new ProxyGenerator(); 
var proxy = generator.CreateInterfaceProxyWithTargetInterface<IService>(new Service(), new MyInterceptor()); 
proxy.InterceptedMethod(); // works 
proxy.SomeMethod(); // Compile error, proxy is an IService 

一兩件事,可以工作在去除的someMethod(該虛擬上),做像這樣

var proxy = generator.CreateClassProxy<Service>(new MyInterceptor()); 

但我不喜歡這個解決方案。

我不喜歡從IProxyGenerationHook中使用ShouldInterceptMethod,因爲每當我更改接口時,我還需要更改ShouldInterceptMethod,也有人某天可以重構方法名稱,並且方法不會被截取。

還有其他方法可以做到這一點嗎?

回答

2

如果要爲類創建代理,則需要使用classproxy。

如果你想排除某些成員,你必須使用IProxyGenerationHook。

如果你想讓你的代碼不可知的改變界面/類的成員像名字簽名被添加或刪除 - 比這樣做!

最簡單的代碼,我能想到的是這樣的:

private InterfaceMap interfaceMethods = typeof(YourClass).GetInterfaceMap(typeof(YourInterface)); 
public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo) 
{ 
    return Array.IndexOf(interfaceMethods.ClassMethods,methodInfo)!=-1; 
}