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?
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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With