问题
I got an interface like this
public interface IService
{
void InterceptedMethod();
}
A class that implements that interface and also has another method
public class Service : IService
{
public virtual void InterceptedMethod()
{
Console.WriteLine("InterceptedMethod");
}
public virtual void SomeMethod()
{
Console.WriteLine("SomeMethod");
}
}
And an Interceptor
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine("Intercepting");
invocation.Proceed();
}
}
I want to intercept only the methods on Service that exists on IService (i.e I want to intercept InterceptedMethod() but not SomeMethod()), but I don't want to use ShouldInterceptMethod from IProxyGenerationHook.
I can do like this, but since its return an Interface, I can't call SomeMethod on this object
var generator = new ProxyGenerator();
var proxy = generator.CreateInterfaceProxyWithTargetInterface<IService>(new Service(), new MyInterceptor());
proxy.InterceptedMethod(); // works
proxy.SomeMethod(); // Compile error, proxy is an IService
One thing that can work is removing the virtual from SomeMethod() and do like this
var proxy = generator.CreateClassProxy<Service>(new MyInterceptor());
But I don't like this solution.
I dont like using ShouldInterceptMethod from IProxyGenerationHook, because everytime that I change the interface I also need to change ShouldInterceptMethod, also someone someday can refactor the method name and the method is not intercepted anymore.
There's any other way to do this?
回答1:
If you want to create a proxy for the class, you need to use classproxy.
If you want to exclude certain members you have to use IProxyGenerationHook.
If you want your code to be agnostic to changes to members of interface/class like names signatures being added or removed - than make it so!
Simplest code I could think of is something like this:
private InterfaceMap interfaceMethods = typeof(YourClass).GetInterfaceMap(typeof(YourInterface));
public bool ShouldInterceptMethod(Type type, MethodInfo methodInfo)
{
return Array.IndexOf(interfaceMethods.ClassMethods,methodInfo)!=-1;
}
来源:https://stackoverflow.com/questions/2109873/intercept-only-interface-methods-with-dynamicproxy