Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

AppDomain.CreateInstanceAndUnwrap Method (String, String, Object[])

Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, the name of the type, and an array of activation attributes.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public Object CreateInstanceAndUnwrap (
	string assemblyName,
	string typeName,
	Object[] activationAttributes
)
public Object CreateInstanceAndUnwrap (
	String assemblyName, 
	String typeName, 
	Object[] activationAttributes
)
public function CreateInstanceAndUnwrap (
	assemblyName : String, 
	typeName : String, 
	activationAttributes : Object[]
) : Object
Not applicable.

Parameters

assemblyName

The display name of the assembly. See Assembly.FullName.

typeName

The fully qualified name of the requested type, including the namespace but not the assembly, as returned by the Type.FullName property.

activationAttributes

An array of one or more attributes that can participate in activation. Typically, an array that contains a single UrlAttribute object. The UrlAttribute specifies the URL that is required to activate a remote object. For a detailed description of client-activated objects, see Client Activation.

Return Value

An instance of the object specified by typeName.

Exception typeCondition

ArgumentNullException

assemblyName or typeName is a null reference (Nothing in Visual Basic).

MissingMethodException

No matching public constructor was found.

TypeLoadException

typename was not found in assemblyName.

FileNotFoundException

assemblyName was not found.

MethodAccessException

The caller does not have permission to call this constructor.

NotSupportedException

The caller cannot provide activation attributes for an object that does not inherit from MarshalByRefObject.

AppDomainUnloadedException

The operation is attempted on an unloaded application domain.

BadImageFormatException

assemblyName is not a valid assembly.

-or-

Version 2.0 or later of the common language runtime is currently loaded and assemblyName was compiled with a later version.

FileLoadException

An assembly or module was loaded twice with two different evidences.

This is a convenience method that combines CreateInstance and ObjectHandle.Unwrap. This method calls the default constructor for typeName.

See AssemblyName for the format of assemblyName. See the Type.FullName property for the format of typeName.

NoteNote:

If you make an early-bound call to a method M of an object of type T1 that was returned by CreateInstanceAndUnwrap, and that method makes an early-bound call to a method of an object of type T2 in an assembly C other than the current assembly or the assembly containing T1, assembly C is loaded into the current application domain. This loading occurs even if the early-bound call to T1.M() was made in the body of a DynamicMethod, or in other dynamically generated code. If the current domain is the default domain, assembly C cannot be unloaded until the process ends. If the current domain later attempts to load assembly C, the load might fail.


using System;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Remoting;

class ADDyno

{

   public static Type CreateADynamicAssembly(ref AppDomain myNewDomain,
					     string executableNameNoExe)
   {

	string executableName = executableNameNoExe + ".exe";

	AssemblyName myAsmName = new AssemblyName();
	myAsmName.Name = executableNameNoExe;
	myAsmName.CodeBase = Environment.CurrentDirectory;

	AssemblyBuilder myAsmBuilder = myNewDomain.DefineDynamicAssembly(myAsmName,
						AssemblyBuilderAccess.RunAndSave);
	Console.WriteLine("-- Dynamic Assembly instantiated.");

	ModuleBuilder myModBuilder = myAsmBuilder.DefineDynamicModule(executableNameNoExe,
								      executableName);

	TypeBuilder myTypeBuilder = myModBuilder.DefineType(executableNameNoExe,
						TypeAttributes.Public,
						typeof(MarshalByRefObject));

	MethodBuilder myFCMethod = myTypeBuilder.DefineMethod("CountLocalFiles",
						MethodAttributes.Public |
						MethodAttributes.Static,
						null,
						new Type[] {  });

	MethodInfo currentDirGetMI = typeof(Environment).GetProperty("CurrentDirectory").GetGetMethod();
	MethodInfo writeLine0objMI = typeof(Console).GetMethod("WriteLine",
				     new Type[] { typeof(string) });
	MethodInfo writeLine2objMI = typeof(Console).GetMethod("WriteLine",
				     new Type[] { typeof(string), typeof(object), typeof(object) });
	MethodInfo getFilesMI = typeof(Directory).GetMethod("GetFiles", 
				new Type[] { typeof(string) });

	myFCMethod.InitLocals = true;

	ILGenerator myFCIL = myFCMethod.GetILGenerator();

	Console.WriteLine("-- Generating MSIL method body...");
	LocalBuilder v0 = myFCIL.DeclareLocal(typeof(string));
	LocalBuilder v1 = myFCIL.DeclareLocal(typeof(int));
	LocalBuilder v2 = myFCIL.DeclareLocal(typeof(string));
	LocalBuilder v3 = myFCIL.DeclareLocal(typeof(string[]));

	Label evalForEachLabel = myFCIL.DefineLabel();
	Label topOfForEachLabel = myFCIL.DefineLabel();

	// Build the method body.

	myFCIL.EmitCall(OpCodes.Call, currentDirGetMI, null);
	myFCIL.Emit(OpCodes.Stloc_S, v0);
	myFCIL.Emit(OpCodes.Ldc_I4_0);
	myFCIL.Emit(OpCodes.Stloc_S, v1);
	myFCIL.Emit(OpCodes.Ldstr, "---");
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);
	myFCIL.Emit(OpCodes.Ldloc_S, v0);
	myFCIL.EmitCall(OpCodes.Call, getFilesMI, null);
	myFCIL.Emit(OpCodes.Stloc_S, v3);

	myFCIL.Emit(OpCodes.Br_S, evalForEachLabel);

	// foreach loop starts here.
	myFCIL.MarkLabel(topOfForEachLabel);
	
        // Load array of strings and index, store value at index for output.
	myFCIL.Emit(OpCodes.Ldloc_S, v3);
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldelem_Ref);
	myFCIL.Emit(OpCodes.Stloc_S, v2);

	myFCIL.Emit(OpCodes.Ldloc_S, v2);
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);

	// Increment counter by one.
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldc_I4_1);
	myFCIL.Emit(OpCodes.Add);
	myFCIL.Emit(OpCodes.Stloc_S, v1);

	// Determine if end of file list array has been reached.
	myFCIL.MarkLabel(evalForEachLabel);
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Ldloc_S, v3);
	myFCIL.Emit(OpCodes.Ldlen);
	myFCIL.Emit(OpCodes.Conv_I4);
	myFCIL.Emit(OpCodes.Blt_S, topOfForEachLabel);
	//foreach loop end here.

	myFCIL.Emit(OpCodes.Ldstr, "---");
	myFCIL.EmitCall(OpCodes.Call, writeLine0objMI, null);
	myFCIL.Emit(OpCodes.Ldstr, "There are {0} files in {1}.");
	myFCIL.Emit(OpCodes.Ldloc_S, v1);
	myFCIL.Emit(OpCodes.Box, typeof(int));
	myFCIL.Emit(OpCodes.Ldloc_S, v0);
	myFCIL.EmitCall(OpCodes.Call, writeLine2objMI, null);

	myFCIL.Emit(OpCodes.Ret);

	Type myType = myTypeBuilder.CreateType();

	myAsmBuilder.SetEntryPoint(myFCMethod);
	myAsmBuilder.Save(executableName);		
	Console.WriteLine("-- Method generated, type completed, and assembly saved to disk."); 

	return myType;

   }

   public static void Main() 
   {

	string domainDir, executableName = null;
	
	Console.Write("Enter a name for the file counting assembly: ");
	string executableNameNoExe = Console.ReadLine();
	executableName = executableNameNoExe + ".exe";
	Console.WriteLine("---");

	domainDir = Environment.CurrentDirectory;

	AppDomain curDomain = Thread.GetDomain();	


	// Create a new AppDomain, with the current directory as the base.

	Console.WriteLine("Current Directory: {0}", Environment.CurrentDirectory);
	AppDomainSetup mySetupInfo = new AppDomainSetup();
	mySetupInfo.ApplicationBase = domainDir;
	mySetupInfo.ApplicationName = executableNameNoExe;
	mySetupInfo.LoaderOptimization = LoaderOptimization.SingleDomain;

	AppDomain myDomain = AppDomain.CreateDomain(executableNameNoExe,
					null, mySetupInfo);

	Console.WriteLine("Creating a new AppDomain '{0}'...",
					executableNameNoExe);

	Console.WriteLine("-- Base Directory = '{0}'", myDomain.BaseDirectory); 
	Console.WriteLine("-- Shadow Copy? = '{0}'", myDomain.ShadowCopyFiles); 

	Console.WriteLine("---");
	Type myFCType = CreateADynamicAssembly(ref curDomain, 
					 executableNameNoExe);

	Console.WriteLine("Loading '{0}' from '{1}'...", executableName,
			  myDomain.BaseDirectory.ToString());


	BindingFlags bFlags = (BindingFlags.Public | BindingFlags.CreateInstance |
			       BindingFlags.Instance);

	Object myObjInstance = myDomain.CreateInstanceAndUnwrap(executableNameNoExe,
				executableNameNoExe, false, bFlags, 
				null, null, null, null, null);

	Console.WriteLine("Executing method 'CountLocalFiles' in {0}...",
			   myObjInstance.ToString());

	myFCType.InvokeMember("CountLocalFiles", BindingFlags.InvokeMethod, null,
				myObjInstance, new object[] { });
			
		
   }

}


import System.*;
import System.IO.*;
import System.Threading.*;
import System.Reflection.*;
import System.Reflection.Emit.*;
import System.Runtime.Remoting.*;

class ADDyno
{
    public static Type CreateADynamicAssembly(AppDomain myNewDomain, 
        String executableNameNoExe) 
    {
        String executableName = executableNameNoExe + ".exe";
        AssemblyName myAsmName =  new AssemblyName();
        myAsmName.set_Name(executableNameNoExe);
        myAsmName.set_CodeBase(Environment.get_CurrentDirectory());

        AssemblyBuilder myAsmBuilder = 
            myNewDomain.DefineDynamicAssembly(myAsmName, 
            AssemblyBuilderAccess.RunAndSave);
        Console.WriteLine("-- Dynamic Assembly instantiated.");

        ModuleBuilder myModBuilder = 
            myAsmBuilder.DefineDynamicModule(executableNameNoExe, 
            executableName);

        TypeBuilder myTypeBuilder = myModBuilder.DefineType(executableNameNoExe,
            TypeAttributes.Public, MarshalByRefObject.class.ToType());

        MethodBuilder myFCMethod = myTypeBuilder.DefineMethod("CountLocalFiles", 
            MethodAttributes.Public | MethodAttributes.Static, null, 
            new Type[]{});

        MethodInfo currentDirGetMI = Environment.class.ToType().
            GetProperty("CurrentDirectory").GetGetMethod();
        MethodInfo writeLine0ObjMI = Console.class.ToType().
            GetMethod("WriteLine", new Type[]{String.class.ToType()});
        MethodInfo writeLine2ObjMI = Console.class.ToType().
            GetMethod("WriteLine", new Type[]{String.class.ToType(), 
            Object.class.ToType(), Object.class.ToType()});
        MethodInfo getFilesMI = Directory.class.ToType().GetMethod("GetFiles", 
            new Type[]{String.class.ToType()});

        myFCMethod.set_InitLocals(true);
        ILGenerator myFCIL = myFCMethod.GetILGenerator();

        Console.WriteLine("-- Generating MSIL method body...");
        LocalBuilder v0 = myFCIL.DeclareLocal(String.class.ToType());
        LocalBuilder v1 = myFCIL.DeclareLocal(int.class.ToType());
        LocalBuilder v2 = myFCIL.DeclareLocal(String.class.ToType());
        LocalBuilder v3 = myFCIL.DeclareLocal(String[].class.ToType());

        Label evalForEachLabel = myFCIL.DefineLabel();
        Label topOfForEachLabel = myFCIL.DefineLabel();

        // Build the method body.
        myFCIL.EmitCall(OpCodes.Call, currentDirGetMI, null);
        myFCIL.Emit(OpCodes.Stloc_S, v0);
        myFCIL.Emit(OpCodes.Ldc_I4_0);
        myFCIL.Emit(OpCodes.Stloc_S, v1);
        myFCIL.Emit(OpCodes.Ldstr, "---");
        myFCIL.EmitCall(OpCodes.Call, writeLine0ObjMI, null);
        myFCIL.Emit(OpCodes.Ldloc_S, v0);
        myFCIL.EmitCall(OpCodes.Call, getFilesMI, null);
        myFCIL.Emit(OpCodes.Stloc_S, v3);

        myFCIL.Emit(OpCodes.Br_S, evalForEachLabel);

        // foreach loop starts here.
        myFCIL.MarkLabel(topOfForEachLabel);

        // Load array of strings and index, store value at index for output.
        myFCIL.Emit(OpCodes.Ldloc_S, v3);
        myFCIL.Emit(OpCodes.Ldloc_S, v1);
        myFCIL.Emit(OpCodes.Ldelem_Ref);
        myFCIL.Emit(OpCodes.Stloc_S, v2);

        myFCIL.Emit(OpCodes.Ldloc_S, v2);
        myFCIL.EmitCall(OpCodes.Call, writeLine0ObjMI, null);

        // Increment counter by one.
        myFCIL.Emit(OpCodes.Ldloc_S, v1);
        myFCIL.Emit(OpCodes.Ldc_I4_1);
        myFCIL.Emit(OpCodes.Add);
        myFCIL.Emit(OpCodes.Stloc_S, v1);

        // Determine if end of file list array has been reached.
        myFCIL.MarkLabel(evalForEachLabel);
        myFCIL.Emit(OpCodes.Ldloc_S, v1);
        myFCIL.Emit(OpCodes.Ldloc_S, v3);
        myFCIL.Emit(OpCodes.Ldlen);
        myFCIL.Emit(OpCodes.Conv_I4);
        myFCIL.Emit(OpCodes.Blt_S, topOfForEachLabel);
        //foreach loop end here.

        myFCIL.Emit(OpCodes.Ldstr, "---");
        myFCIL.EmitCall(OpCodes.Call, writeLine0ObjMI, null);
        myFCIL.Emit(OpCodes.Ldstr, "There are {0} files in {1}.");
        myFCIL.Emit(OpCodes.Ldloc_S, v1);
        myFCIL.Emit(OpCodes.Box, int.class.ToType());
        myFCIL.Emit(OpCodes.Ldloc_S, v0);
        myFCIL.EmitCall(OpCodes.Call, writeLine2ObjMI, null);

        myFCIL.Emit(OpCodes.Ret);

        Type myType = myTypeBuilder.CreateType();

        myAsmBuilder.SetEntryPoint(myFCMethod);
        myAsmBuilder.Save(executableName);
        Console.WriteLine("-- Method generated, type completed, "
            + "and assembly saved to disk.");

        return myType;
    } //CreateADynamicAssembly

    public static void main(String[] args)
    {
        String executableName = null;
        String domainDir;

        Console.Write("Enter a name for the file counting assembly: ");
        String executableNameNoExe = Console.ReadLine();
        executableName = executableNameNoExe + ".exe";
        Console.WriteLine("---");

        domainDir = Environment.get_CurrentDirectory();
        AppDomain curDomain = System.Threading.Thread.GetDomain();

        // Create a new AppDomain, with the current directory as the base.
        Console.WriteLine("Current Directory: {0}", 
            Environment.get_CurrentDirectory());
        AppDomainSetup mySetupInfo =  new AppDomainSetup();
        mySetupInfo.set_ApplicationBase(domainDir);
        mySetupInfo.set_ApplicationName(executableNameNoExe);
        mySetupInfo.set_LoaderOptimization(LoaderOptimization.SingleDomain);

        AppDomain myDomain = AppDomain.CreateDomain(executableNameNoExe, null, 
            mySetupInfo);

        Console.WriteLine("Creating a new AppDomain '{0}'...", 
            executableNameNoExe);
        Console.WriteLine("-- Base Directory = '{0}'", myDomain.get_BaseDirectory());
        Console.WriteLine("-- Shadow Copy? = '{0}'", 
            (System.Boolean)myDomain.get_ShadowCopyFiles());
        Console.WriteLine("---");

        Type myFCType = CreateADynamicAssembly(curDomain, executableNameNoExe);
        Console.WriteLine("Loading '{0}' from '{1}'...", executableName, 
            myDomain.get_BaseDirectory().ToString());

        BindingFlags bFlags = BindingFlags.Public | BindingFlags.CreateInstance 
            | BindingFlags.Instance;

        Object myObjInstance = 
            myDomain.CreateInstanceAndUnwrap(executableNameNoExe, 
            executableNameNoExe, false, bFlags, null, null, null, null, null);

        Console.WriteLine("Executing method 'CountLocalFiles' in {0}...", 
            myObjInstance.ToString());

        myFCType.InvokeMember("CountLocalFiles", BindingFlags.InvokeMethod, 
            null, myObjInstance, new Object[]{});
   } //main
} //ADDyno 

Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft