Skip to main content
 首页 » 编程设计

C# 在 Assembly.Load 时避免文件锁定

2024年02月13日37小虾米

我的情况是;

我正在设计一个基于动态加载插件程序集的插件应用程序,多个用户可以运行托管在服务器计算机上的应用程序。应用程序在启动时从我的实时更新服务器自动更新插件程序集。因此插件文件(及其附属 dll 不应锁定在文件系统上。

 byte[] assemblyBytes = File.ReadAllBytes("asm-path"); 
 var assembly = Assembly.Load(assemblyBytes); 

如预期的那样没有锁定 dll 文件。但是如果我正在加载的 dll 本身有静态引用 dll 怎么办?它们现在被锁定在文件系统上。

命名文件,比方说;

  • APP.Exe 是我的基础应用程序;
  • PL1.dll 是我的第一个插件,APP.exe 将它加载到一个新的 App 域中
  • PL2.dll 是我的第二个插件,APP.exe 将它加载到一个新的 App 域中
  • PL1_S.dll是PL1.dll插件的静态引用dll,加载到PL1 AppDomain
  • PL_COMMON 是 PL1 和 PL2 插件的静态引用 dll,由 PL1 和 PL2 AppDomains 加载

PL1_S 和 PL_COMMON 也不应该像 PL1 和 PL2 程序集一样锁定在文件中

关于如何解决这个问题有什么想法吗?

请您参考如下方法:

已经内置了执行此操作的功能,例如ASP.Net。参见 Shadow Copying Assemblies :

Shadow copying enables assemblies that are used in an application domain to be updated without unloading the application domain. This is particularly useful for applications that must be available continuously, such as ASP.NET sites.

所以只需通过 AppDomainSetup.ShadowCopyFiles 打开它在创建您的 AppDomain

时