- 应用程序域的概念
应用程序域为隔离正在运行的应用程序提供了一种灵活而安全的方法。
应用程序域通常由运行库宿主创建和操作。有时,您可能希望应用程序以编程方式与应用程序域交互,例如想在不停止应用程序运行的情况下卸载某个组件时。
应用程序域使应用程序以及应用程序的数据彼此分离,有助于提高安全性。单个进程可以运行多个应用程序域,并具有在单独进程中所存在的隔离级别。在单个进程中运行多个应用程序提高了服务器伸缩性。
- 应用程序域调用外部程序集
- 编码方法
可以使用 ExecuteAssembly 或 ExecuteAssemblyByName ,或者使用这些方法的其他重载版本之一。
如果想从默认入口点以外的位置执行另一个程序集,可在远程程序集中定义一个从
MarshalByRefObject
派生的新类型。然后在应用程序中使用
CreateInstance
创建该类型的一个实例。例如:定义下面的程序,编译生成程序集.
// This namespace contains code to be called.
namespace HelloWorldRemote
{
public class RemoteObject : System.MarshalByRefObject
{
public RemoteObject()
{
System.Console.WriteLine("Hello, World! (RemoteObject Constructor)");
}
}
class Program
{
static void Main()
{
System.Console.WriteLine("Hello, World! (Main method)");
}
}
}
用AppDomain来实现程序集的加载,并执行.
static void Main()
{
System.AppDomain NewAppDomain = System.AppDomain.CreateDomain("NewApplicationDomain");
// Load the assembly and call the default entry point:
NewAppDomain.ExecuteAssembly(@"c:/HelloWorldRemote.exe");
// Create an instance of RemoteObject:
NewAppDomain.CreateInstanceFrom(@"c:/HelloWorldRemote.exe", "HelloWorldRemote.RemoteObject");
System.AppDomain.Unload(newDomain);
}
用Assembley类来直接加载程序集,并执行相关代码.
static void Main()
{
// Load the assembly into the current appdomain:
System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFrom(@"c:/HelloWorldRemote.exe");
// Instantiate RemoteObject:
newAssembly.CreateInstance("HelloWorldRemote.RemoteObject");
}
- 手动加载
如果不想以编程方式加载程序集,可以从“解决方案资源管理器”中使用“添加引用”来指定程序集 HelloWorldRemote.exe。然后向应用程序的 using 块中添加一个 using HelloWorldRemote;
指令,并在程序中使用 RemoteObject 类型来声明 RemoteObject 对象的一个实例,如下所示:
{
// This code creates an instance of RemoteObject, assuming HelloWorldRemote has been added as a reference:
HelloWorldRemote.RemoteObject o = new HelloWorldRemote.RemoteObject();
}
-
程序域概述
应用程序域具有以下特点:
-
必须先将程序集加载到应用程序域中,然后才能执行该程序集。
-
一个应用程序域中的错误不会影响在另一个应用程序域中运行的其他代码。
-
能够在不停止整个进程的情况下停止单个应用程序并卸载代码。不能卸载单独的程序集或类型,只能卸载整个应用程序域。