How Moles Isolation framework is implemented?(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 框架是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Moles Isolation 框架是如何实现的?


- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01