Ruslan Muradasilov
Ruslan Muradasilov

Reputation: 113

How to dynamically add an instance method to type from loaded assembly in runtime?

I have .NET 6.0 app which dynamically loads .NET Framework 4.8 assembly. Calling method from this assembly with reflection throws this exception:

System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.

By including a reference to System.Reflection.Emit, I found out that method DefineDynamicAssembly does not exist in AppDomain in .NET Core. Loaded assembly calls AppDomain.CurrentDomain.DefineDynamicAssembly() and failing to find the method throws exception.

So I decided to add this new method dynamically in runtime and unsuccessfully tried two following approaches:

  1. The first approach assumes defining a new method by MethodBuilder using TypeBuilder and ILGenerator. The problem is that I create an instance of TypeBuilder from ModelBuilder.DefineType() which defines a new type but I need to hook up to the existing instance of AppDomain.CurrentDomain;
  2. The second approach uses DymanicMethod. Unfortunately, this approach does not allow to create instance methods (only public static ones).

Is there any other way to solve this problem? Or maybe I am missing something in the above approaches? I will appreciate any advice!

Upvotes: 1

Views: 376

Answers (0)

Related Questions