应用程序域

  • 应用程序域的概念

应用程序域为隔离正在运行的应用程序提供了一种灵活而安全的方法。

应用程序域通常由运行库宿主创建和操作。有时,您可能希望应用程序以编程方式与应用程序域交互,例如想在不停止应用程序运行的情况下卸载某个组件时。

应用程序域使应用程序以及应用程序的数据彼此分离,有助于提高安全性。单个进程可以运行多个应用程序域,并具有在单独进程中所存在的隔离级别。在单个进程中运行多个应用程序提高了服务器伸缩性。

  • 应用程序域调用外部程序集
  • 编码方法
最简单的加载方法是使用 AssemblyLoad ,它会将程序集加载到当前应用程序域中,并从程序集的默认入口点开始运行代码。
可以使用 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 对象的一个实例,如下所示:

static void Main()
{
    // This code creates an instance of RemoteObject, assuming HelloWorldRemote has been added as a reference:
    HelloWorldRemote.RemoteObject o = new HelloWorldRemote.RemoteObject();
}
  • 程序域概述

应用程序域具有以下特点:

  • 必须先将程序集加载到应用程序域中,然后才能执行该程序集。

  • 一个应用程序域中的错误不会影响在另一个应用程序域中运行的其他代码。

  • 能够在不停止整个进程的情况下停止单个应用程序并卸载代码。不能卸载单独的程序集或类型,只能卸载整个应用程序域。

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值