public sealed class AppDomain : MarshalByRefObject, _AppDomain, IEvidenceFactory
|
Multiple application domains can run in a single process; however, there is not a one-to-one correlation between application domains and threads. Several threads can belong to a single application domain, and while a given thread is not confined to a single application domain, at any given time, a thread executes in a single application domain.
Application domains are created using the AppDomain.CreateDomain method. AppDomain instances are used to load and execute assemblies ( Assembly). When a AppDomain is no longer in use, it can be unloaded.
The AppDomain class implements a set of events that enable applications to respond when an assembly is loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.
For more information about using application domains, see the list of Frequently Asked Questions at gotdotnet/team/clr/appdomainfaq.aspx
This class implements the MarshalByRefObject, _AppDomain, and IEvidenceFactory interfaces.
| BaseDirectory | Read-only Gets the base directory that the assembly resolver used to probe for assemblies. |
| CurrentDomain | Read-only Gets the current application domain for the current Thread. |
| DynamicDirectory | Read-only Gets the directory that the assembly resolver used to probe for dynamically-created assemblies. |
| Evidence | Read-only Gets the Evidence associated with this application domain that is used as input to the security policy. |
| FriendlyName | Read-only Gets the friendly name of this application domain. |
| RelativeSearchPath | Read-only Gets the path relative to the base directory where the assembly resolver should probe for private assemblies. |
| SetupInformation | Read-only Gets the application domain configuration information for this instance. |
| ShadowCopyFiles | Read-only Gets an indication whether all assemblies loaded in the application domain are shadow copied. |
| AppendPrivatePath | Appends the specified name of the directory to the private path. |
| ClearPrivatePath | Resets the path that specifies the location of private assemblies to the empty string (""). |
| ClearShadowCopyPath | Resets the list of directories containing shadow copied assemblies to the empty string (""). |
| CreateDomain | Overloaded:CreateDomain(string friendlyName) Creates a new application domain with the specified name. |
| CreateDomain | Overloaded:CreateDomain(string friendlyName, Evidence securityInfo) Creates a new application domain with the given name using the supplied evidence. |
| CreateDomain | Overloaded:CreateDomain(string friendlyName, Evidence securityInfo, AppDomainSetup info) Creates a new application domain using the specified name, evidence, and application domain setup information. |
| CreateDomain | Overloaded:CreateDomain(string friendlyName, Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles) Creates a new application domain with the given name, using evidence, application base path, relative search path, and a parameter that specifies whether a shadow copy of an assembly is to be loaded into the application domain. |
| CreateInstance | Overloaded:CreateInstance(string assemblyName, string typeName) Creates a new instance of the specified type defined in the specified assembly. |
| CreateInstance | Overloaded:CreateInstance(string assemblyName, string typeName, object[] activationAttributes) Creates a new instance of the specified type defined in the specified assembly. A parameter specifies an array of activation attributes. |
| CreateInstance | Overloaded:CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes) Creates a new instance of the specified type defined in the specified assembly. Parameters specify a binder, binding flags, constructor arguments, culture-specific information used to interpret arguments, activation attributes, and authorization to create the type. |
| CreateInstanceAndUnwrap | Overloaded:CreateInstanceAndUnwrap(string assemblyName, string typeName) Creates a new instance of the specified type. Parameters specify the assembly where the type is defined, and the name of the type. |
| CreateInstanceAndUnwrap | Overloaded:CreateInstanceAndUnwrap(string assemblyName, string typeName, object[] activationAttributes) 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. |
| CreateInstanceAndUnwrap | Overloaded:CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes) Creates a new instance of the specified type. Parameters specify the name of the type, and how it is found and created. |
| CreateInstanceFrom | Overloaded:CreateInstanceFrom(string assemblyFile, string typeName) Creates a new instance of the specified type defined in the specified assembly file. |
| CreateInstanceFrom | Overloaded:CreateInstanceFrom(string assemblyFile, string typeName, object[] activationAttributes) Creates a new instance of the specified type defined in the specified assembly file. |
| CreateInstanceFrom | Overloaded:CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes) Creates a new instance of the specified type defined in the specified assembly file. |
| CreateInstanceFromAndUnwrap | Overloaded:CreateInstanceFromAndUnwrap(string assemblyName, string typeName) Creates a new instance of the specified type defined in the specified assembly file. |
| CreateInstanceFromAndUnwrap | Overloaded:CreateInstanceFromAndUnwrap(string assemblyName, string typeName, object[] activationAttributes) Creates a new instance of the specified type defined in the specified assembly file. |
| CreateInstanceFromAndUnwrap | Overloaded:CreateInstanceFromAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, Evidence securityAttributes) Creates a new instance of the specified type defined in the specified assembly file. |
| CreateObjRef (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) Defines a dynamic assembly with the specified name and access mode. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence) Defines a dynamic assembly using the specified name, access mode, and evidence. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir) Defines a dynamic assembly using the specified name, access mode, and storage directory. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence) Defines a dynamic assembly using the specified name, access mode, storage directory, and evidence. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions) Defines a dynamic assembly using the specified name, access mode, and permission requests. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions) Defines a dynamic assembly using the specified name, access mode, evidence, and permission requests. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions) Defines a dynamic assembly using the specified name, access mode, storage directory, and permission requests. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions) Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, and permission requests. |
| DefineDynamicAssembly | Overloaded:DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, string dir, Evidence evidence, PermissionSet requiredPermissions, PermissionSet optionalPermissions, PermissionSet refusedPermissions, bool isSynchronized) Defines a dynamic assembly using the specified name, access mode, storage directory, evidence, permission requests, and synchronization option. |
| DoCallBack | Executes the code in another application domain that is identified by the specified delegate. |
| Equals (inherited from System.Object) |
See base class member description: System.Object.Equals Derived from System.Object, the primary base class for all objects. |
| ExecuteAssembly | Overloaded:ExecuteAssembly(string assemblyFile) Executes the assembly contained in the specified file. |
| ExecuteAssembly | Overloaded:ExecuteAssembly(string assemblyFile, Evidence assemblySecurity) Executes the assembly contained in the specified file, using the specified evidence. |
| ExecuteAssembly | Overloaded:ExecuteAssembly(string assemblyFile, Evidence assemblySecurity, string[] args) Executes the assembly contained in the specified file, using the specified evidence and arguments. |
| GetAssemblies | Gets the assemblies that have been loaded into this application domain. |
| GetCurrentThreadId | Gets the current thread identifier. |
| GetData | Gets the value stored in the current application domain for the specified data name. |
| GetHashCode (inherited from System.Object) |
See base class member description: System.Object.GetHashCode Derived from System.Object, the primary base class for all objects. |
| GetLifetimeService (inherited from System.MarshalByRefObject) |
See base class member description: System.MarshalByRefObject.GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. |
| GetType (inherited from System.Object) |
See base class member description: System.Object.GetType Derived from System.Object, the primary base class for all objects. |
| InitializeLifetimeService | Overridden: Gives the AppDomain an infinite lifetime by preventing a lease from being created. |
| IsFinalizingForUnload | Indicates whether this application domain is unloading, and the objects it contains are being finalized by the common language runtime. |
| Load | Overloaded:Load(AssemblyName assemblyRef) Loads an Assembly given its AssemblyName. |
| Load | Overloaded:Load(byte[] rawAssembly) Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. |
| Load | Overloaded:Load(string assemblyString) Loads an Assembly given its display name. |
| Load | Overloaded:Load(AssemblyName assemblyRef, Evidence assemblySecurity) Loads an Assembly given its AssemblyName. |
| Load | Overloaded:Load(byte[] rawAssembly, byte[] rawSymbolStore) Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded. |
| Load | Overloaded:Load(string assemblyString, Evidence assemblySecurity) Loads an Assembly given its display name. |
| Load | Overloaded:Load(byte[] rawAssembly, byte[] rawSymbolStore, Evidence securityEvidence) Loads the Assembly with a common object file format (COFF) based image containing an emitted Assembly. The raw bytes representing the symbols for the Assembly are also loaded. |
| SetAppDomainPolicy | Establishes the security policy level for this application domain. |
| SetCachePath | Establishes the specified directory path as the location where assemblies are shadow copied. |
| SetData | Assigns the specified value to the specified application domain property. |
| SetDynamicBase | Establishes the specified directory path as the location where dynamically generated files are stored and accessed. |
| SetPrincipalPolicy | Specifies how principal and identity objects should be attached to a thread if the thread attempts to bind to a principal while executing in this application domain. |
| SetShadowCopyFiles | Turns on shadow copying. |
| SetShadowCopyPath | Establishes the specified directory path as the location of assemblies to be shadow copied. |
| SetThreadPrincipal | Sets the default principal object to be attached to threads if they attempt to bind to a principal while executing in this application domain. |
| ToString | Overridden: Obtains the String representation of this instance. |
| Unload | Unloads the specified application domain. |
| AssemblyLoad | Occurs when an assembly is loaded. |
| AssemblyResolve | Occurs when the resolution of an assembly fails. |
| DomainUnload | Occurs when an AppDomain is about to be unloaded. |
| ProcessExit | Occurs on the default application domain when the default application domain's parent process exits. |
| ResourceResolve | Occurs when the resolution of a resource fails. |
| TypeResolve | Occurs when the resolution of a type fails. |
| UnhandledException | Occurs when an exception is not caught by an event handler. |
| Finalize (inherited from System.Object) |
See base class member description: System.Object.Finalize Derived from System.Object, the primary base class for all objects. |
| MemberwiseClone (inherited from System.Object) |
See base class member description: System.Object.MemberwiseClone Derived from System.Object, the primary base class for all objects. |
Hierarchy:
public string BaseDirectory {get;}
|
public static AppDomain CurrentDomain {get;}
|
public string DynamicDirectory {get;}
|
public Evidence Evidence {get;}
|
public string FriendlyName {get;}
|
"c:\MyAppDirectory\MyAssembly.exe"
is loaded in the default application domain, the friendly name of that application domain is
"MyAssembly.exe"
.
public string RelativeSearchPath {get;}
|
public AppDomainSetup SetupInformation {get;}
|
public bool ShadowCopyFiles {get;}
|
public void AppendPrivatePath( |
path
public void ClearPrivatePath(); |
For more information, see AppDomainSetup.PrivateBinPath.
public void ClearShadowCopyPath(); |
For more information, see AppDomainSetup.ShadowCopyDirectories.
friendlyName
| Exception Type | Condition |
|---|---|
| ArgumentNullException | friendlyName is null. |
// Set up the AppDomainSetup
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "(some directory)";
setup.ConfigurationFile = "(some file)";
// Set up the Evidence
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
evidence.AddAssembly("(some assembly)");
evidence.AddHost("(some host)");
// Create the AppDomain
AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);
friendlyName
securityInfo
// Set up the AppDomainSetup
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "(some directory)";
setup.ConfigurationFile = "(some file)";
// Set up the Evidence
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
evidence.AddAssembly("(some assembly)");
evidence.AddHost("(some host)");
// Create the AppDomain
AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);
-or-
for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain
public static AppDomain CreateDomain( |
friendlyName
securityInfo
info
// Set up the AppDomainSetup
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "(some directory)";
setup.ConfigurationFile = "(some file)";
// Set up the Evidence
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
evidence.AddAssembly("(some assembly)");
evidence.AddHost("(some host)");
// Create the AppDomain
AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);
-or-
for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain
public static AppDomain CreateDomain( |
friendlyName
securityInfo
appBasePath
appRelativeSearchPath
shadowCopyFiles
// Set up the AppDomainSetup
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = "(some directory)";
setup.ConfigurationFile = "(some file)";
// Set up the Evidence
Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
Evidence evidence = new Evidence(baseEvidence);
evidence.AddAssembly("(some assembly)");
evidence.AddHost("(some host)");
// Create the AppDomain
AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);
-or-
for the ability to create and manipulate an AppDomain. Associated enumeration: SecurityPermissionFlag/ControlAppDomain
public ObjectHandle CreateInstance( |
assemblyName
typeName
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName or typeName is null. |
| 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. |
See AssemblyName for the format of assemblyName.
public ObjectHandle CreateInstance( |
assemblyName
typeName
activationAttributes
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName or typeName is null. |
| 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. |
See AssemblyName for the format of assemblyName.
public ObjectHandle CreateInstance( |
assemblyName
typeName
ignoreCase
bindingAttr
binder
args
culture
activationAttributes
securityAttributes
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName or typeName is null. |
| MissingMethodException | No matching 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. |
See AssemblyName for the format of assemblyName.
using System;
using System.Reflection;
using System.Globalization;
class MySimpleBinder : Binder {
public override MethodBase BindToMethod(
BindingFlags bindingAttr,
MethodBase[] match,
ref object[] args,
ParameterModifier[] modifiers,
CultureInfo culture,
string[] names,
out object state
) {
if (args[0] is string) {
args[0] = ChangeType(args[0], typeof(double), culture);
}
return Type.DefaultBinder.BindToMethod(
bindingAttr,
match,
ref args,
modifiers,
culture,
names,
out state
);
}
public override object ChangeType(
object value,
Type type,
CultureInfo culture
) {
return Convert.ChangeType(value, type, culture.NumberFormat);
}
public override FieldInfo BindToField(
BindingFlags bindingAttr,
FieldInfo[] match,
object value,
CultureInfo culture
) {
throw new NotImplementedException();
}
public override MethodBase SelectMethod(
BindingFlags bindingAttr,
MethodBase[] match,
Type[] types,
ParameterModifier[] modifiers
) {
throw new NotImplementedException();
}
public override PropertyInfo SelectProperty(
BindingFlags bindingAttr,
PropertyInfo[] match,
Type returnType,
Type[] indexes,
ParameterModifier[] modifiers
) {
throw new NotImplementedException();
}
public override void ReorderArgumentArray(
ref object[] args,
object state
) {
throw new NotImplementedException();
}
}
class Test {
static void Main() {
InstantiateDecimal(null, null);
// Fails to instantiate
InstantiateDecimal(new MySimpleBinder(), new CultureInfo("en-US"));
// Instantiates new Decimal(9.999d)
InstantiateDecimal(new MySimpleBinder(), new CultureInfo("de-DE"));
// Instantiates new Decimal(9999d)
}
// Attempts instantiation of a Decimal object with a string argument
// using the given Binder and CultureInfo object.
static void InstantiateDecimal(Binder binder, CultureInfo cultureInfo) {
try {
AppDomain currentDomain = AppDomain.CurrentDomain;
object instance = currentDomain.CreateInstanceAndUnwrap(
"mscorlib",
"System.Decimal",
false,
BindingFlags.Default,
binder,
new object[] { "9.999" },
cultureInfo,
null,
null
);
Console.WriteLine(instance);
} catch (MissingMethodException e) {
Console.WriteLine(e.Message);
}
}
}
assemblyName
typeName
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName or typeName is null. |
| 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. |
See AssemblyName for the format of assemblyName.
public object CreateInstanceAndUnwrap( |
assemblyName
typeName
activationAttributes
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName or typeName is null. |
| 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. |
See AssemblyName for the format of assemblyName.
public object CreateInstanceAndUnwrap( |
assemblyName
typeName
ignoreCase
bindingAttr
binder
args
culture
activationAttributes
securityAttributes
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName or typeName is null. |
| MissingMethodException | No matching 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. |
See AssemblyName for the format of assemblyName.
using System;
using System.Reflection;
class Test {
static void Main() {
InstantiateINT32(false); // Failed!
InstantiateINT32(true); // OK!
}
static void InstantiateINT32(bool ignoreCase) {
try {
AppDomain currentDomain = AppDomain.CurrentDomain;
object instance = currentDomain.CreateInstanceAndUnwrap(
"mscorlib",
"SYSTEM.INT32",
ignoreCase,
BindingFlags.Default,
null,
null,
null,
null,
null
);
Console.WriteLine(instance.GetType());
} catch (TypeLoadException e) {
Console.WriteLine(e.Message);
}
}
}
public ObjectHandle CreateInstanceFrom( |
assemblyFile
typeName
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyFile is null. -or- typeName is null. |
For more information, see the Activator.CreateInstanceFrom method.
public ObjectHandle CreateInstanceFrom( |
assemblyFile
typeName
activationAttributes
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyFile is null. -or- typeName is null. |
For more information, see the Activator.CreateInstanceFrom method.
public ObjectHandle CreateInstanceFrom( |
assemblyFile
typeName
ignoreCase
bindingAttr
binder
args
culture
activationAttributes
securityAttributes
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyFile is null. -or- typeName is null. |
assemblyName
typeName
-or-
null if typeName is not found.
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName is null. -or- typeName is null. |
For more information, see the Activator.CreateInstanceFrom method.
public object CreateInstanceFromAndUnwrap( |
assemblyName
typeName
activationAttributes
-or-
null if typeName is not found.
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName is null. -or- typeName is null. |
For more information, see the Activator.CreateInstanceFrom method.
public object CreateInstanceFromAndUnwrap( |
assemblyName
typeName
ignoreCase
bindingAttr
binder
args
culture
activationAttributes
securityAttributes
-or-
null if typeName is not found.
| Exception Type | Condition |
|---|---|
| ArgumentNullException | assemblyName is null. -or- typeName is null. |
For more information, see the Activator.CreateInstanceFrom method.
requestedType
| Exception Type | Condition |
|---|---|
| RemotingException | This instance is not a valid remoting object. |
public AssemblyBuilder DefineDynamicAssembly( |
name
access
| Exception Type | Condition |
|---|---|
| ArgumentNullException | name is null. |
| ArgumentException | The Name property of name is null. -or- The Name property of name begins with white space, or contains a forward or backward slash. |
The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.
using System;
using System.Reflection;
using System.Reflection.Emit;
class Test {
public static void Main() {
AppDomain currentDomain = AppDomain.CurrentDomain;
InstantiateMyDynamicType(currentDomain); // Failed!
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
InstantiateMyDynamicType(currentDomain); // OK!
}
static void InstantiateMyDynamicType(AppDomain domain) {
try {
domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
return DefineDynamicAssembly((AppDomain) sender);
}
static Assembly DefineDynamicAssembly(AppDomain domain) {
// Build a dynamic assembly using Reflection Emit API.
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;
}
}
public AssemblyBuilder DefineDynamicAssembly( |
name
access
evidence
| Exception Type | Condition |
|---|---|
| ArgumentNullException | name is null. |
| ArgumentException | The Name property of name is null. -or- The Name property of name begins with white space, or contains a forward or backward slash. |
If the dynamic Assembly is saved to disk, subsequent loads will get grants based on policies associated with the location where the Assembly was saved.
This method should only be used to define a dynamic assembly in the current application domain. For more information, see the Remarks section of the topic.
The name parameter indirectly specifies a Version (as an OperatingSystem.#ctor constructor parameter). However, this method only persists the major and minor version numbers, not the build and revision numbers. For example, if the Assembly.LoadFrom method is used to indirectly recover the Version for this assembly, only that object's major and minor version numbers will be as originally specified.
using System;
using System.Reflection;
using System.Reflection.Emit;
class Test {
public static void Main() {
AppDomain currentDomain = AppDomain.CurrentDomain;
InstantiateMyDynamicType(currentDomain); // Failed!
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
InstantiateMyDynamicType(currentDomain); // OK!
}
static void InstantiateMyDynamicType(AppDomain domain) {
try {
domain.CreateInstance("MyDynamicAssembly", "MyDynamicType");
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
return DefineDynamicAssembly((AppDomain) sender);
}
static Assembly DefineDynamicAssembly(AppDomain domain) {
// Build a dynamic assembly using Reflection Emit API.
AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "MyDynamicAssembly";
AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
Module