Is it possible to write an assembly that dynamically generates a new class and corrects itself with a new class?

Is it possible to write an assembly that dynamically generates / emits a new class and schedules itself to include a new class?

How?

+4
source share
2 answers

I asked this question in another way: Using AssemblyBuilder, how can I make all or any related assemblies assembled instead of a link in a saved assembly?

Fixing an existing dll with dynamically generated code will lead to the same thing as embedding the original dll in dynamically generated code - one assembly with the contents of both.

It seems that one way or another, to eliminate dependencies and pack the contents of several assemblies into one, ILMerge is the most elegant solution.

The only problem is that the types generated in the merged dll are not compatible with the same types in both source dlls. If the source DLL, for example, emits a new assembly, combines it with itself and loads the new assembly ... it cannot use its own types to denote things in the new assembly that correspond to the same type in any of the original assemblies.

In other words: Class A in the links [dll_generator] [dll_1]. Class A generates [dll_2], which is based on and, of course, also references [dll_1]. Class A calls ILMerge to combine [dll_2] with its dependency [dll_1] to create [dll_merged]. None of the types in [dll_merged] are compatible with any of their source types in [dll_1] and [dll_2], so if class A loads [dll_merged] and tries to do something with it, including literal type names from it of the original link to [dll_1], it fails because the types are incompatible. The only way that class A can work with types in [dll_merged] is to load them by name and fully work with objects and the Type reflection or dynamically compile the source code for the new [dll_merged].

+2
source

The best way to do this is to use injection / inversion of control dependencies or even a simple service locator.

Your new assembly will create a new concrete implementation and register that instead of the old implementation.

I'm sure something more exotic would be a terrible hack.

+1
source

All Articles