Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding method in DLL using reflection

Tags:

c#

reflection

dll

I am not even sure if this is possible so apologies if not. I have googled quite extensively and not found what I am looking for.

Basically we have an application produced by a third party, which, to be perfectly blunt is rubbish. We have a particular issue and have managed to trace the problem using ILSpy to a method within a DLL. Obviously we don't have (nor are able to get) the source code and the company in question is unwilling to fix the problem in any reasonable timescales.

So, we've investigated various avenues of investigation and come up with nothing. I've been looking into seeing whether this can be done using reflection and this is pretty much the last hope we have of getting this to work. In a nutshell, what I would like to do is the following:

  • Create a simple class library with the same name as the existing DLL
  • Use reflection to import the methods from the existing DLL
  • Somehow override the method in question with my own, correct code
  • Rebuild the code, so I have a new DLL, containing 99% of the functionality of the existing DLL but with my override code providing the correct functionality.

I have found, during my investigations TypeBuilder.DefineMethodOverride and also a page from StackOverflow, which seems similar but not quite what I am looking for.

http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.definemethodoverride.aspx

Is there a way to "override" a method with reflection?

Any advice appreciated!

Andrew

Edit

The other possible idea I has was to produce a partial class containing the override function, but that didn't seem feasible either.

like image 356
Andrew Avatar asked Jun 18 '13 13:06

Andrew


1 Answers

You can override the method only if it is virtual, and it doesn't matter whether you do it through reflection or statically. I would suggest using a decompiler (there are a lot of free ones available) and fixing the code in MSIL. Then you can generate a new assembly from the MSIL.

like image 156
Marek Dzikiewicz Avatar answered Oct 11 '22 00:10

Marek Dzikiewicz