Moq 和 NHibernate 如何自动创建派生类型?
使用 NHibernate 时,您可以使用虚拟方法定义实体,NHibernate 将创建一个代理对象来跟踪对象的更改。
在 Moq 中,框架会神奇地从接口或基类创建派生类型。 例如,
var mock = new Mock<IFoo>();
IFoo magicFoo = mock.Object;
这真的很酷。 这些框架是如何做到的呢? 他们使用反射、泛型、某种动态编译还是其他什么?
我意识到这些都是开源项目,我可以深入研究代码,但我想在这里得到一个简洁的答案 - 可能还有替代方案。
When using NHibernate, you define your entites with virtual methods, and NHibernate will create a proxy object that tracks changes to your object.
In Moq, the framework will magically create a derived type from an interface or a base class. e.g.
var mock = new Mock<IFoo>();
IFoo magicFoo = mock.Object;
This is really cool. How do these frameworks do it? Do they use reflection, generics, some kind of dynamic compilation, or something else?
I realize these are both open source projects, and I could go spelunking through the code, but I'd like to have a concise answer here - possibly with alternatives.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Moq 使用 Castle 动态代理,但是,只是认为值得添加还有许多其他框架允许您创建代理对象。 从 NHibernate 2.1 开始,它还允许您使用以下任何一种:
每个项目都有一个关于如何实现这一目标的简要说明,希望是这样的回答您正在寻找的问题。
Moq uses Castle Dynamic Proxy, however, just thought it would be worth adding there are also a number of other frameworks that allow you to create Proxy objects. As of NHibernate 2.1 it also allows you to use any one of the following:
Each of these projects has a brief explaination of how they achieve this, which is hopefully the kind of answer you're looking for.
它们结合使用反射(找出需要生成的内容)和反射发出(动态生成派生类,并为方法发出 IL)。 .NET 提供了这两种 API(反射和反射发出)。
They use a combination of reflection (to figure out what needs to be generated) and reflection-emit (to generate the derived class dynamically, and emitting IL for the methods). .NET provides both of these APIs (reflection and reflection-emit).
Castle 的 DynamicProxy2 类。
Castle's DynamicProxy2 class.