views:

145

answers:

2

Hello,

According to MSDN MethodRental Class allows to change method body of dynamic modules. However because of its limitations I cannot think of practical usages for it. Google did not help me either.

Any ideas what the class can be used for?

+3  A: 

Not sure what limitations you mean. Clearly this can only work on dynamically generated methods, produced by MethodBuilder. Class methods that were JIT compiled from IL loaded from an assembly cannot be replaced.

A use case would be implementing a runtime for a dynamic language that supports altering the methods of already defined classes (monkey patching). Languages like Ruby, Python, Javascript etc.

Hans Passant
+2  A: 

This is similar in spirit to ICorProfilerCallback::JITCompilationStarted when paired with ICorProfilerInfo::SetILFunctionBody, but with more constraints. The ICorProfiler* classes can be used to do runtime instrumentation for almost any managed method. There are profilers and debuggers that use these to collect information about a running process.

You could use MethodRental to instrument code for diagnostic purposes. Some examples:

  • Function enter/exit would give you an execution trace that you could use to derive profiling data from.
  • Instrumenting synchronization primitives can help you diagnose race conditions.
  • Instrumenting basic blocks can help you determine code coverage.

You could also use MethodRental to enhance the functionality of existing code. Aspect-oriented programming comes to mind. You could 'weave' in security, logging, or other cross-cutting design concerns into existing code. This would require some other facility (XML, a C# library) to express your aspects, however.

Finally, you could use MethodRental to "detour" existing code, i.e. intercept method calls to create a kind of runtime polymorphism. For example, if you have client code that uses some dynamically-generated class RegistryStore to get some configuration via GetConfig, you could rewrite the method's IL to change the implementation of RegistryStore.GetConfig to use the filesystem instead. You could do this without having to change the client code.

Chris Schmich
@Chris - You cannot use MethodRental for AOP as it supports only dynamic methods, can you?
Giorgi
@Giorgi: sorry, I didn't mean to be misleading. You can use it for AOP, but you'll still have the same constraints that `MethodRental` imposes: specifically, that you can only use it on dynamic methods/assemblies. Depending on what you're trying to do, that might not be useful at all. All of the uses I listed have that same fundamental constraint, though.
Chris Schmich
@Chris: Thanks for your answer. As the constraint is very limited that's because I could not think of a possible usage.
Giorgi