【问题标题】:Runtime loading of private assemblies in a subdirectory子目录中私有程序集的运行时加载
【发布时间】:2014-10-23 14:42:56
【问题描述】:

我一直在尝试加载位于应用程序基目录下的子目录中的私有程序集。我有一个名为 Sparrow.dll 的程序集,它位于 plugins 目录下(也位于应用程序基础目录下)。每当我调用 Assembly.Load("Sparrow") 时,我都会收到 System.IO.FileNotFoundException。

我使用了带有标记的 app.exe.config,它与下面一行相同的程序集的强命名版本一起使用;

Assembly assem = Assembly.Load("Sparrow");

但是,当我将程序集更改为弱程序集时,它不起作用。

配置文件的内容如下;

<configuration>
    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly name="Sparrow, Culture=neutral, PublicKeyToken=xxxxxx">
            <codeBase version="1.0.1.1" href="plugins/Sparrow.dll" />
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
</configuration>

我读了很多东西,但我不确定使用标记来定位弱程序集是否是一个好习惯。

【问题讨论】:

  • 您在使用弱命名程序集时是否设置了PublicKeyToken=null
  • @JeanHominal:是的,我做到了。

标签: c# .net .net-assembly assembly-resolution


【解决方案1】:

您可以为此目的使用probing 元素:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="plugins" />
    </assemblyBinding>
  </runtime>
</configuration>

该元素意味着将在 plugins 子文件夹中搜索程序集。 但是请注意,只有在应用程序目录的后代路径上的目录才能以这种方式指定。

您问题中的配置文件有错误。根据文档,XML 配置应如下所示:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
     <dependentAssembly>
       <assemblyIdentity name="Sparrow"
                          publicKeyToken="null"
                          culture="neutral" />
       <codeBase version="1.0.1.1" href="plugins/Sparrow.dll" />
     </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

但是,我认为在您的情况下使用 probing 元素会是更好的选择。

【讨论】:

  • 这正是我解决问题的方法。对于弱和私有的程序集,它非常简单,并且据我所知也很好用。但是,有很多关于程序集的信息会导致混淆。据我从 MSDN 中了解到,将 用于弱程序集是可能且可行的。
  • @Deniz:您是否使用了带有privatePath 属性的probing 元素?因为我在您的问题中看不到这一点-您使用了不同的元素。此外,您当前的解决方案不能很好地适应带有插件的系统,因为您需要为要添加的每个插件修改配置文件。
  • 不是这个问题,但我在我的电脑上测试过。你是对的,如果我为不同的插件使用不同的文件夹,那么我应该添加它们中的每一个。可能将每个程序集放入单个文件夹(为插件程序集保留)可以简化问题。我当然愿意接受不同的解决方案。
  • @Deniz:重新阅读您的问题后,我发现&lt;dependentAssembly&gt; 元素中有错误。这对你有什么好处吗?
  • 你是对的。但仍然无法正常工作。顺便说一句,.NET 允许这样的错误有点奇怪,不是吗?
猜你喜欢
  • 2012-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-05
  • 2011-09-09
  • 1970-01-01
相关资源
最近更新 更多