Application domain is a construct in the CLR that is the unit of isolation for an application. The isolation guarantees the following:
An application can be independently stopped.
An application cannot directly access code or resources in another application.
A fault in an application cannot affect other applications.
Configuration information is scoped by application. This means that an application controls the location from which code is loaded and the version of the code that is loaded.
the follow code shows how to invoke the SayHello method in the
HelloWorld2 assembly:
using System;
using System.Reflection;
using System.Runtime.Remoting;
public class InvokeMethod
{
public static void Main( String[] argv )
{
// Set ApplicationBase to the current directory
AppDomainSetup info = new AppDomainSetup();
info.ApplicationBase = "file:///" +
System.Environment.CurrentDirectory;
// Create an application domain with null evidence
AppDomain dom = AppDomain.CreateDomain("RemoteDomain", null, info);
// Load the assembly HelloWorld2 and instantiate the type
// HelloWorld
BindingFlags flags = (BindingFlags.Public | BindingFlags.Instance |
BindingFlags.CreateInstance);
ObjectHandle objh = dom.CreateInstance("HelloWorld2", "HelloWorld",
false, flags, null, new String[]{"Hello World!"}, null, null, null);
if (objh == null) {
Console.WriteLine("CreateInstance failed");
return;
}
// Unwrap the object
Object obj = objh.Unwrap();
// Cast to the actual type
HelloWorld h = (HelloWorld)obj;
// Invoke the method
h.SayHello();
// Clean up by unloading the application domain
AppDomain.Unload(dom);
}
}
where the HelloWorld2 is,
using System;
using System.Threading;
public class HelloWorld : MarshalByRefObject
{
private String _greeting;
public HelloWorld(String greeting)
{
if (greeting == null) {
throw new ArgumentNullException("Null greeting!");
}
_greeting = greeting;
}
public void SayHello()
{
Console.WriteLine("In the application domain: " +
Thread.GetDomain().FriendlyName);
Console.WriteLine(_greeting);
}
}
Note:
Ensure the type containing the method to be invoked derives
from System.MarshalByRefObject. This is necessary to ensure that the
type is marshaled by reference across the boundary of the created
application domain.
By default it is System.MarshalValueRefObject.
System._AppDomain interface :
The System._AppDomain interface is meant for use by unmanaged code that
needs access to the members of the managed System.AppDomain class.
Unmanaged code calls the methods of the System._AppDomain interface
through COM Interop. Unmanaged code can obtain a pointer to the
_AppDomain interface by calling QueryInterface on the default domain.
Regards,
Satheesh