.NET 4.0中的动态程序集加载

10

我的问题始于将一个 .Net 2.0 应用程序迁移到 .Net 4.0。我必须这样做的原因是 Windows 8 默认情况下不启用更早的 .Net 版本,而我的应用程序无法要求用户启用它。

该应用程序是一个使用 .Net 组件通过 UnmanagedExports 的 NPAPI 插件。我将其设计为低完整性应用程序,因此必须驻留在用户的 'LocalLow' 目录中。

在我的应用程序中,我使用了动态装配加载机制来在运行时加载多个装配件。我使用以下方法来加载一个装配件:

MyInterface Instance;

Assembly assembly = Assembly.LoadFrom(AssemblyFile);
Type type = assembly.GetType(Identifier); // Identifier is implementing the MyInterface 
Instance = Activator.CreateInstance(type) as MyInterface;

// Do something with the Instance

将项目修改为 .Net 4.0 后,我发现插件在放置在 LocalLow 目录内的二进制文件中崩溃(但在其他地方运行正常)。我的下一步是创建一个最小化的插件,并使用尽可能少的代码来找出问题。我发现动态装配加载失败并出现以下异常:

System.IO.FileLoadException: Could not load file or assembly '<assemblyPath>' or one of its dependencies. Operation is not supported. (Exception from HRESULT: 0x80131515 (COR_E_NOTSUPPORTED)) --->

System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=131738 for more information.

我尝试了以下方法来创建一个独立的域并加载程序集,但没有成功:

添加配置项“loadFromRemoteSources”也没有起作用。似乎.NET组件不会加载.dll.config文件。(可能是因为UnmanagedExporting)

我的问题是,

  • 是否可能从LocalLow中动态加载程序集?
  • CLR 4.0中的新CAS策略是否也适用于LocalLow?根据我的理解,它只应该影响通过网络加载的程序集。
  • 有没有其他方法可以克服这个问题?

1
你为什么在LocalLow目录下?这是一个专门被保护的目录,只允许不受信任的应用程序(低完整性进程)进行写入操作。由于它被用于Internet Explorer和其他浏览器,所以它可能被视为“网络位置”,但它也可能只是dll上的MOTW。 - Mitch
我不得不切换到LocalLow的原因是,当运行插件时,Internet Explorer会阻止访问所有其他路径,特别是如果我们要写入文件时。请查看此链接。唯一的选择是使用LocalLow。 - Isuru
1
正是我的观点。由于它可以被插件写入,.Net会将其列入黑名单,以防止加载程序集。LocalLow用于需要被插件写入的文件,而不是插件本身。请在另一个目录中找到插件(例如Program Files),并将临时数据文件写入LocalLow。 - Mitch
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接