我的问题始于将一个 .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.
我尝试了以下方法来创建一个独立的域并加载程序集,但没有成功:
- http://blogs.msdn.com/b/shawnfa/archive/2009/06/08/more-implicit-uses-of-cas-policy-loadfromremotesources.aspx
- http://www.west-wind.com/weblog/posts/2009/Jan/19/Assembly-Loading-across-AppDomains
添加配置项“loadFromRemoteSources”也没有起作用。似乎.NET组件不会加载.dll.config文件。(可能是因为UnmanagedExporting)
我的问题是,
- 是否可能从LocalLow中动态加载程序集?
- CLR 4.0中的新CAS策略是否也适用于LocalLow?根据我的理解,它只应该影响通过网络加载的程序集。
- 有没有其他方法可以克服这个问题?