Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a method implementation at runtime?

I'd like to have property getters and methods that I can decorate with my own custom attribute and based on the presence of that attribute replace the method bodies with a different implementation. Also, that different implementation will need to know the constructor arguments given to the custom attribute where it decorates the method.

This can obviously be done with AOP, like PostSharp or LinFu, but I'm wondering if there's a way to do this that does not involve a post-build processing step because adding that complicates the project more than I would prefer.

like image 879
quentin-starin Avatar asked Jan 22 '23 21:01

quentin-starin


2 Answers

There exists a couple of frameworks that allows you to dynamically change any method at runtime:

  • Harmony Free and Open Source (MIT)!
  • Prig: Free and Open Source (MIT), requires Visual Studio extension and running programs under a launcher, not updated since 2017.
  • Microsoft Fakes: Commercial, included in Visual Studio Enterprise (Premium and Ultimate for older versions) but not Community and Professional
  • Telerik JustMock: Commercial, a "lite" version is available
  • Typemock Isolator: Commercial
like image 68
poizan42 Avatar answered Jan 24 '23 13:01

poizan42


Using the traditional .Net APIs there is no way to achieve this. Method bodies are fixed at compile time and cannot be changed.

I say traditional though because with the profiler and ENC APIs it's technically possible to change method bodies. But these APIs operate in constrained circumstances and are not considered to be general purpose APIs.

like image 21
JaredPar Avatar answered Jan 24 '23 12:01

JaredPar