如何为反射操作加载 .NET 程序集并随后卸载它? [英] How to load a .NET assembly for reflection operations and subsequently unload it?

查看:19
本文介绍了如何为反射操作加载 .NET 程序集并随后卸载它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个工具来报告有关在客户系统内跨环境和区域部署的 .NET 应用程序的信息.

I'm writing a tool to report information about .NET applications deployed across environments and regions within my client's systems.

我想读取这些程序集中的程序集属性值.

I'd like to read the values of assembly attributes in these assemblies.

这可以通过使用 Assembly.ReflectionOnlyLoad 来实现,但是即使这种方法也会保持程序集加载.这里的问题是我无法从不同的路径加载两个具有相同名称的程序集,因此我自然无法比较部署在不同系统中的相同应用程序.

This can be achieved using Assembly.ReflectionOnlyLoad, however even this approach keeps the assembly loaded. The issue here is that I cannot load two assemblies that have the same name from different paths, so naturally I can't compare the same application deployed in different systems.

此时我假设解决方案将涉及使用临时 AppDomains.

At this point I'm assuming the solution will involve using temporary AppDomains.

有人可以详细说明如何将程序集加载到另一个 AppDomain,从中读取属性,然后卸载 AppDomain 吗?

Can someone detail how to load an assembly into another AppDomain, read the attributes from it and then unload the AppDomain?

这需要适用于文件系统上的程序集以及 URL 地址上的程序集.

This needs to work for assemblies on the file system as well as those at URL addresses.

推荐答案

来自 System.Reflection.Assembly.ReflectionOnlyLoad (String) 的 MSDN 文档 :

仅反射上下文为 no与其他语境不同.装入的程序集上下文只能由卸载应用程序域.

The reflection-only context is no different from other contexts. Assemblies that are loaded into the context can be unloaded only by unloading the application domain.

所以,恐怕卸载程序集的唯一方法就是卸载应用程序域.要创建新的 AppDomain 并将程序集加载到其中:

So, I am afraid the only way to unload an assembly is unloading the application domain. To create a new AppDomain and load assemblies into it:

public void TempLoadAssembly()
{
    AppDomain tempDomain = AppDomain.CreateDomain("TemporaryAppDomain");
    tempDomain.DoCallBack(LoaderCallback);
    AppDomain.Unload(tempDomain);
}

private void LoaderCallback()
{
    Assembly.ReflectionOnlyLoad("YourAssembly");
    // Do your stuff here
}

这篇关于如何为反射操作加载 .NET 程序集并随后卸载它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆