.NET 7.0 项目参考:在运行时加载外部类库 DLL 时出现“无法加载文件或程序集”

问题描述 投票:0回答:0

我正在创建一个类库 DLL (.NET 7.0),并且我正在尝试测试从控制台应用程序 (.NET 7.0) 引用该 DLL。 Visual Studio 检测到代码中的所有引用,并且根本没有生成错误。当我运行控制台应用程序时,一旦它尝试调用引用 DLL,它就会抛出异常:

5/9/2023 12:12:33 PM|Error|WebSocket.messages|System.IO.FileNotFoundException: Could not load file or assembly 'ExampleSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.
                       File name: 'ExampleSharp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
                          at ExampleSharpDemo.Connection.OnMessage(MessageEventArgs e)
                          at WebSocketSharp.Server.WebSocketBehavior.onMessage(Object sender, MessageEventArgs e)
                          at WebSocketSharp.Ext.Emit[TEventArgs](EventHandler`1 eventHandler, Object sender, TEventArgs e)
                          at WebSocketSharp.WebSocket.messages(MessageEventArgs e)

这是我的 ExampleSharpDemo 的 .csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NETCore.Encrypt" Version="2.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="WebSocketSharp-netstandard" Version="1.0.1" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="ExampleWebSockets">
      <HintPath>..\..\ExampleWebSockets\ExampleWebSockets\bin\Release\net7.0\publish\win-x86\ExampleWebSockets.dll</HintPath>
    </Reference>
    <Reference Include="ExampleSharp">
      <HintPath>..\ExampleSharp\bin\Release\net7.0\publish\win-x86\ExampleSharp.dll</HintPath>
      <Private>True</Private>
    </Reference>
  </ItemGroup>

</Project>

这是我的 ExampleSharp 的 .csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="NETCore.Encrypt" Version="2.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="ExampleWebSockets">
      <HintPath>..\..\ExampleWebSockets\ExampleWebSockets\bin\Release\net7.0\publish\win-x86\ExampleWebSockets.dll</HintPath>
    </Reference>
  </ItemGroup>


</Project>

我已经尝试过重建,将其作为 x86 运行,删除引用并再次添加。我还加载了“ExampleSharp”的“ExampleWebSockets”和“NETCore.Encrypt”依赖项。我不知道为什么它无法加载程序集。我在多个 dependency walkers 中打开它,它们似乎都能很好地检测到它。

编辑: 我也试过使用 Procmon 来查看为什么无法加载依赖项,但它似乎发现文件已找到,结果为“FILE LOCKED WITH ONLY READERS”?我很困惑。

附加信息: 我计划将此类库作为外部 DLL 分发。最终用户(开发人员)将无法访问“ExampleSharp”的源代码。所以,我不能直接包含项目参考。虽然,我会提到当我直接包含项目参考时,它工作正常并且我没有得到这个异常。

有什么我想念的吗? .NET 7.0 不就是为了这个吗?

谢谢

c# .net visual-studio .net-assembly .net-7.0
© www.soinside.com 2019 - 2024. All rights reserved.