How do Moq and NHibernate automatically create derived types?

佐手、 提交于 2019-12-11 00:31:36

问题


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.


回答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:

  • Castle Dynamic Proxy
  • LinFu Framework
  • Spring.NET

Each of these projects has a brief explaination of how they achieve this, which is hopefully the kind of answer you're looking for.




回答2:


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




回答3:


Castle's DynamicProxy2 class.



来源:https://stackoverflow.com/questions/1275433/how-do-moq-and-nhibernate-automatically-create-derived-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!