2010-01-21 59 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; 
}