How will u load dynamic assembly? How will create assemblies
at run time?

Answer Posted / ruena

You can create an assembly at runtime in the following
way...

The following example creates an assebly, class within it
and also defines the main method.

You can use dynamic invocation methods to execute the
assembly.

Make use of System.Reflection and System.Reflection.Emit
namespaces. Hope you find this useful.

public static void Main()
{
// 1.
// Create a new dynamic assembly
AssemblyName assemblyName = new AssemblyName
("DynamicHelloWorld");
AssemblyBuilder dynamicAssembly =
AppDomain.CurrentDomain.DefineDynamicAssembly(
assemblyName,

AssemblyBuilderAccess.RunAndSave);

// 2.
// Create a module inside the assembly
ModuleBuilder dynamicModule =
dynamicAssembly.DefineDynamicModule(

assemblyName.Name,
"DynamicHelloWorld
.exe");

//3.
// Create a type inside the module
TypeBuilder programType =
dynamicModule.DefineType(
"DynamicHelloWorld.Pro
gram",
TypeAttributes.Class
| TypeAttributes.Public);

// 4.
// Add a method
MethodBuilder main = programType.DefineMethod(
"Main",
MethodAttributes.Public |
MethodAttributes.Static,
null,
null);

// 5.
// Add the IL for the method. The IL is
equivalent to
// Console.WriteLine("Hello, world!");
Type console = typeof(Console);
MethodInfo writeLine = console.GetMethod(
"WriteLine",
new Type[] { typeof
(string) });

ILGenerator il = main.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Hello, world!");
il.Emit(OpCodes.Call, writeLine);

// 6.
// Set the return value to 0
//il.Emit(OpCodes.Ldc_I4_0);
//il.Emit(OpCodes.Ret);

// 7.
// Now we're done, materialize the type
programType.CreateType();

// 8.
// Set the program's entry point to the Main
method
dynamicAssembly.SetEntryPoint(main,
PEFileKinds.ConsoleApplication);

// 9.
// Save the assembly
dynamicAssembly.Save("DynamicHelloWorld.exe");

Console.Write("Dynamic Assembly Emitted...");
}

Is This Answer Correct ?    4 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is value type and refernce type in .net?

666


what are connection strings?

1857


What is Complex Class in .NET?

687


What is Entity Relationship Model in .NET?

669


What are virtual destructures?

609






What are the main components in .net?

627


Can any object be stored in a viewstate in .net?

683


Do you know what are three common acronyms used in .net, and what do they stand for?

644


How do you create threading in.net?

638


How to debug failed assembly binds?

680


Differentiate between 'DataSet' and 'SQLDataReader' in ADO.NET?

677


What are the challenging issues you have faced in implementation project/Maintainance project in .net Functionality? How you have overcome that issue?

4683


Is .net a programming language?

625


Can you create instance of a class which has private constructor?

670


What are nullable types in .NET

718