接口方法我喜歡這個攔截只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,也有人某天可以重構方法名稱,並且方法不會被截取。
還有其他方法可以做到這一點嗎?