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

后端 未结 5 886
我在风中等你
我在风中等你 2021-01-13 21:26

Suppose I have the following .NET classes:

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

and

public class         


        
相关标签:
5条回答
  • 2021-01-13 21:47

    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.

    0 讨论(0)
  • 2021-01-13 21:50

    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.

    0 讨论(0)
  • 2021-01-13 22:00

    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

    0 讨论(0)
  • 2021-01-13 22:04

    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

    0 讨论(0)
  • 2021-01-13 22:13

    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)

    0 讨论(0)
提交回复
热议问题