开发者

Intercept only interface methods with DynamicProxy

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 : IInterce开发者_如何学JAVAptor
{
    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?


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜