Can I redirect .NET method calls to a new method at runtime?

泄露秘密 提交于 2019-12-30 10:10:53

问题


Suppose I have the following .NET classes:

public class C
{
    public void M()
    {
        ....
    }
}

and

public class D
{
    public void N()
    {
        ....
    }
}

These 2 classes reside in different namespaces, in different assemblies. Is there a way to cause all call to C.M() to 'redirect' automatically to D.N()? So, the calling method things its invoking C.M, but in reality, D.N is what actually gets called, with any parameters that C.M would have taken. It doesn't matter if this happens for all instantiations of the class, or just for one specific object.

MS Research has the Detours Library that can do something very similar for normal Win32 DLL exports. I'm looking for a way to do this with a .NET method.


回答1:


Microsoft has created a managed equivalent to Detours called Moles. The only thing I'm not sure of is the licensing; it is intended for testing (as part of Pex).

Dependency injection requires modifying the source; PostSharp requires modifying the binary; but Moles can be done dynamically at runtime.




回答2:


There are mainly two possible approaches - proxying the objects or hooking the calls.

Proxying can be done using Castle Dynamic Proxy or any similar dynamic proxy framework. Hooking the calls can either be done with aspect oriented programming with something like PostSharp or even by black magic like done by Isolator (it is designed for unit testing but it can probably be (ab)used like all other technologies)




回答3:


I suspect you could do some IL weaving with PostSharp.

I did find this nice article on using other tools too : http://blog.andreloker.de/post/2009/02/14/Simple-AOP-call-interception-with-DynamicProxy.aspx




回答4:


Try Dependency Injection?

Modify C to:

public class C
{
    public void M()
    {
        if (Override != null) { Override.N(); }
        else {
            ....
        }
    }

    public D Override
}

If you need more flexibility, Extract Interface from class D.




回答5:


Yes you can

Please see this http://www.codeproject.com/Articles/463508/Net-CLR-Injection-Modify-IL-Codes-on-Run-time

You can do that by modifying the IL code on runtime



来源:https://stackoverflow.com/questions/3145346/can-i-redirect-net-method-calls-to-a-new-method-at-runtime

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