How Moles Isolation framework is implemented?

后端 未结 2 1444
臣服心动
臣服心动 2020-12-02 17:42

Moles is an isolation framework created by Microsoft. A cool feature of Moles is that it can \"mock\" static/non-virtual methods and sealed classes (which is not possible w

2条回答
  •  暖寄归人
    2020-12-02 18:06

    Moles implements a CLR profiler (in particular the ICorProfilerCallback interface) that allows to rewrite MSIL method bodies before they are compiled into assembly code by the .NET runtime. This is done in particular through the JitCompileStarted callback.

    In each method, Moles introduces a detour that looks like this:

    static struct DateTime 
    {
        static DateTime Now
        {
            get 
            {
                Func d = __Detours.GetDelegate(
                    null, // this point null in static methods
                    methodof(here) // current method token
                    );
                if(d != null)
                    return d();
                ... // original body
            }
        }
    }
    

    When you set a mole, your delegate is stored in the underlying __Detours dictionary which gets looked up whenver the method is executed.

提交回复
热议问题