拦截网卡与DynamicProxy方法
-
22-09-2019 - |
题
我喜欢这个
的接口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(即我想截距InterceptedMethod(),但不是的someMethod())的方法中,但我不希望使用ShouldInterceptMethod从IProxyGenerationHook。
我可以这样做,但由于它的返回一个接口,我不能叫上的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());
,但我不喜欢该溶液中。
我不喜欢使用ShouldInterceptMethod从IProxyGenerationHook,因为每次我更改界面我也需要改变ShouldInterceptMethod,也有人一天可以重构的方法名称和方法不再被截获。
有任何其他方式做到这一点?
解决方案
如果你想创建该类的代理,你需要使用classproxy。
如果您想要排除某些成员必须使用IProxyGenerationHook。
如果你希望你的代码是不可知的变化对接口的成员/添加或删除类似名字的签名类 - 不是令其如此
最简单的代码,我能想到的是这样的:
private InterfaceMap interfaceMethods = typeof(YourClass).GetInterfaceMap(typeof(YourInterface));
public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo)
{
return Array.IndexOf(interfaceMethods.ClassMethods,methodInfo)!=-1;
}
不隶属于 StackOverflow