Intercept only interface methods with DynamicProxy

眉间皱痕 提交于 2019-12-06 12:39:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!