Moles Isolation 框架是如何实现的? [英] How Moles Isolation framework is implemented?

查看:16
本文介绍了Moles Isolation 框架是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Moles 是微软创建的隔离框架.Moles 的一个很酷的特性是它可以模拟"静态/非虚拟方法和密封类(这在像 Moq 这样的框架中是不可能的).下面是 Moles 的快速演示:

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 with frameworks like Moq). Below is the quick demonstration of what Moles can do:

Assert.AreNotEqual(new DateTime(2012, 1, 1), DateTime.Now);

// MDateTime is part of Moles; the below will "override" DateTime.Now's behavior
MDateTime.NowGet = () => new DateTime(2012, 1, 1); 
Assert.AreEqual(new DateTime(2012, 1, 1), DateTime.Now);

似乎 Moles 能够在运行时修改诸如 DateTime.Now 之类的 CIL 主体.由于 Moles 不是开源的,我很想知道 Moles 使用哪种机制来在运行时修改方法的 CIL.任何人都可以解释一下吗?

Seems like Moles is able to modify the CIL body of things like DateTime.Now at runtime. Since Moles isn't open-source, I'm curious to know which mechanism Moles uses in order to modify methods' CIL at runtime. Can anyone shed any light?

推荐答案

Moles 实现了一个 CLR 分析器(特别是 ICorProfilerCallback 接口)允许在 MSIL 方法体被 .NET 运行时编译成汇编代码之前重写它们.这尤其是通过 JitCompileStarted 回调来完成的.

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.

在每种方法中,Moles 都会引入如下所示的绕道:

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

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

当你设置一个mole时,你的委托被存储在底层的__Detours字典中,每当方法被执行时就会被查找.

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

这篇关于Moles Isolation 框架是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆