7

So I am interested in the way that it is implemented. Basically: How can I re-implement the same thing myself? ... which I am not intending to do. Just understand.

The fundamental question is: How is it possible to (?) intercept class instantiation at all? And how can it be replaced in one case with one implementation and in another occurence with it's original or an even different implementation?

How is it even possible to intercept static methods or sealed classes.

This is all about shims/moles not so much about stubs.

Robetto
  • 739
  • 7
  • 20
  • Microsoft solved this issue using the darkest eldritch magic. – Gusdor Aug 13 '14 at 08:53
  • It is not clear to me what the question means by "microsoft fakes' shims" - could you clarify please? – Sander Aug 13 '14 at 11:25
  • @Sander: Microsoft Fakes is a quality tool for unit tests included since VS2012. The main features are shims and stubs. – Robetto Aug 13 '14 at 14:49

1 Answers1

6

This is done by changing the Common Intermediate Language (IL) code that is emitted by the compiler. You can do pre-packaged IL modification using the Fody library. Fody internally uses the mono.cecil library for the low level IL manipulation. The IL generated by the compiler is modified and saved to disk as an assembly.

I have found this reference publication on Moles [pdf file]. Section 4 explains the mechanism of the code instrumentation.

softveda
  • 10,858
  • 6
  • 42
  • 50
  • Are you sure? Shimmed methods are drastically slower than the original object. – Gusdor Aug 13 '14 at 08:55
  • 1
    In the PDF mentioned in the answer I found the following core explanation: The instrumentation is done as follows. At the beginning of each method some code is inserted. This code queries a low-level detours library as to whether any detour was attached to this particular method. If so, then the detour delegate is invoked, otherwise, the normal code is executed. – Robetto Aug 13 '14 at 15:02