Defines a dynamic assembly using the specified name, access mode, and storage directory. : AppDomain « Reflection « C# / C Sharp






Defines a dynamic assembly using the specified name, access mode, and storage directory.

  

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) {
      return DefineDynamicAssembly((AppDomain) sender);
   }

   static Assembly DefineDynamicAssembly(AppDomain domain) {
      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;
   }
}

   
    
  








Related examples in the same category

1.Get AppDomainSetup
2.Assembly loaded event
3.AppDomain.AssemblyResolve Event
4.Gets the base directory that the assembly resolver uses to probe for assemblies.
5.Resets the path that specifies the location of private assemblies to the empty string ("").
6.Creates a new instance of a specified COM type.
7.Creates a new instance of the specified type.
8.Creates a new instance of the specified type defined in the specified assembly file.
9.Gets the current application domain for the current Thread.
10.Gets the friendly name of this application domain.
11.Gets the assemblies that have been loaded into the execution context of this application domain.
12.Loads an Assembly given its AssemblyName.
13.Returns the assemblies that have been loaded into the reflection-only context of the application domain.
14.Establishes security policy level for application domain.
15.Assigns the specified value to the specified application domain property.
16.Get App Setting String