DefineDynamicAssembly method and AssemblyResolve event. : Assembly « Reflection « C# / CSharp Tutorial






using System;
using System.Reflection;
using System.Reflection.Emit;

class Test {
   public static void Main() {
      AppDomain currentDomain = AppDomain.CurrentDomain;

      currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);

      InstantiateMyDynamicType(currentDomain);
   }

   static void InstantiateMyDynamicType(AppDomain domain) {
      try {
         domain.CreateInstance("Assembly text name, Version, Culture, PublicKeyToken", "MyDynamicType");
      } catch (Exception e) {
         Console.WriteLine(e.Message);
      }
   }   

   static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
      AppDomain domain = (AppDomain) sender;
      AssemblyName assemblyName = new AssemblyName();
      assemblyName.Name = "MyDynamicAssembly";

      AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
      ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MyDynamicModule");
      TypeBuilder typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
      ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null);
      ILGenerator ilGenerator = constructorBuilder.GetILGenerator();

      ilGenerator.EmitWriteLine("MyDynamicType instantiated!");
      ilGenerator.Emit(OpCodes.Ret);

      typeBuilder.CreateType();

      return assemblyBuilder;
   }
}








19.12.Assembly
19.12.1.Load Assembly from Dll
19.12.2.Reflecting An Assembly
19.12.3.Reflecting On A Type
19.12.4.Execute Assembly
19.12.5.Search member method in Assembly
19.12.6.Assembly Tree Viewer
19.12.7.DefineDynamicAssembly method and AssemblyResolve event.
19.12.8.Assembly makes internal types and internal members visible to the assembly called your_assemblies.
19.12.9.Use the file name to load the assembly into the current application domain.