如何痣隔离框架的实施? [英] How Moles Isolation framework is implemented?

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

问题描述

是由微软创建的隔离框架。痣的一个很酷的功能是它可以模拟静态/非虚方法和密封类(这是不可能的框架,如MOQ)。下面是快速演示一下痣可以这样做:

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);

看起来像痣是能够在运行时修改的东西CIL身体像 DateTime.Now 。由于痣是不是开源的,我很好奇,想知道哪些机构痣使用,以便修改方法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?

推荐答案

痣实现一个CLR探查器(尤其是的 ICorProfilerCallback 接口),允许重写MSIL方法体之前,他们是由.NET运行时编译成汇编code。这是通过href="http://msdn.microsoft.com/en-us/library/ms230586.aspx"> 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.

在每一种方法是,每介绍一个弯路,看起来像这样:

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
        }
    }
}

当你设置一个痣,您的代理存储在底层__Detours字典它获取抬头whenver执行的方法。

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

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

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