How to add code to DLL at runtime

Let's say in the constructor of my .NET class, I want to write code that will dynamically add methods to my class. So now when I reflect on my class, I will see methods where when when the first time the project was created the methods did not exist

How can I achieve this?

I searched CodeDom but it was all a little confusing

+1


a source to share


5 answers


Once you load the assembly, you cannot change it. You can use Reflection.Emit or CodeDom to dynamically compile a new assembly with a class that is similar to your + additional methods, but it will not change the existing (at least in runtime) class. Potentially, you could load your class into a separate AppDomain, create a new class that was a "copy" of it with additional functionality, and then load that assembly into the main AppDomain (and unload the one where you loaded your original class). You are still creating a new class without adding it to the existing one, but the effect will be the same.



You can use code injection to inject your code before loading the class. There is some code injection framework for .NET to help with this ... but this is different from your specific question.

+3


a source


you need to either use Reflection.Emit or Mono.Cecil or PostSharp.



They are all easy to learn ...

+1


a source


I ... can't imagine why you would want to do this.

Could you please explain why you want?

Try using different concrete implementations of the same interface instead, or an abstract class if you are using most of the code.

0


a source


You can do this without learning anything extra using CInject (open source at Codeplex). Write the code you want to enter in C # or VB.NET, and then process it through CInject to add it to a managed assembly.

0


a source


I agree with @ reed-copsey using appdomain domcomplie functions. You can create a plugin class that inherits from the base plugin class, you can add all the classes you want. When it compiles to appdomain it will even be able to give you the coding errors that were introduced into this class. Then it will not compile this specfic class. At the very least, you will find out that the code has problems.

0


a source







All Articles