接口方法我喜欢这个拦截只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,也有人某天可以重构方法名称,并且方法不会被截取。
还有其他方法可以做到这一点吗?