应用程序解析另一个项目中引用的程序集版本不正确

Application resolving incorrect version of assembly referenced in another project

提问人:G_Hosa_Phat 提问时间:2/24/2023 最后编辑:G_Hosa_Phat 更新时间:2/25/2023 访问量:219

问:

环境:

Microsoft Visual Studio Community 2022(64 位)
版本 17.4.4
Microsoft .NET Framework
版本 4.8.04084

Windows 10 专业版 (x64)
版本:21H2 操作系统内部版本:19044.2486

项目信息:

包含两 (2) 个项目的解决方案(调试配置)

项目 1 (VB.NET):

  • 应用类型:类库
  • 目标框架:.NET Framework 4.8
  • 目标 CPU:x64Target CPU: x64

项目二(VB.NET):

  • 应用类型:Windows 窗体应用程序
  • 目标框架:.NET Framework 4.8
  • 目标 CPU:x64Target CPU: x64

在我的类库项目中,我有一个 Nuget 引用,另一个 Nuget 包 (v7.0.2) 需要它。Nuget 包引用专门标识 v7.0.0。我什至在库中具有绑定重定向,以将对库其他版本的引用指向 v7.0.0,如下所示:Microsoft.Extensions.Logging.AbstractionsNpgsqlMicrosoft.Extensions.Logging.Abstractionsapp.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      [...]
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Logging" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
      [...]
    </assemblyBinding>
  </runtime>
</configuration>

但是,当我尝试从 IDE 运行代码时,每次尝试创建新对象时,它都会抛出一个异常,指出(请注意列出的版本):NpgsqlConnection

Could not load file or assembly 'Microsoft.Extensions.Logging.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' or one of its dependencies. The system cannot find the file specified.

异常的 FusionLog 属性读取(已编辑):

=== Pre-bind state information ===
LOG: DisplayName = Microsoft.Extensions.Logging.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
 (Fully-specified)
LOG: Appbase = file://SERVER/Programming/My Application/bin/Debug/
LOG: Initial PrivatePath = NULL
Calling assembly : Npgsql, Version=7.0.2.0, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: \\SERVER\Programming\My Application\bin\Debug\My Application.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 6.0.0.0 redirected to 6.0.0.0.
LOG: Post-policy reference: Microsoft.Extensions.Logging.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
LOG: Attempting download of new URL file://SERVER/Programming/My Application/bin/Debug/Microsoft.Extensions.Logging.Abstractions.DLL.
LOG: Attempting download of new URL file://SERVER/Programming/My Application/bin/Debug/Microsoft.Extensions.Logging.Abstractions/Microsoft.Extensions.Logging.Abstractions.DLL.
LOG: Attempting download of new URL file://SERVER/Programming/My Application/bin/Debug/Microsoft.Extensions.Logging.Abstractions.EXE.
LOG: Attempting download of new URL file://SERVER/Programming/My Application/bin/Debug/Microsoft.Extensions.Logging.Abstractions/Microsoft.Extensions.Logging.Abstractions.EXE.

我没有对 Windows 窗体应用程序项目中的库的引用:Microsoft.Extensions.Logging.Abstractions

References in Windows Forms Application project

该项目的文件中也没有任何绑定重定向。App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="Project.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <startup>
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
    </startup>
    <userSettings>
        <Project.My.MySettings>
            <setting name="LastPosition" serializeAs="String">
                <value>-1, -1</value>
            </setting>
            <setting name="LastSize" serializeAs="String">
                <value>-1, -1</value>
            </setting>
        </Project.My.MySettings>
    </userSettings>
</configuration>

根据对类似问题“无法加载文件或程序集 Microsoft.Extensions.DependencyInjection.Abstractions,Version=1.1.0.0”的公认答案,我检查了该文件并发现那里列出了绑定重定向(再次,请注意版本):My Project.exe.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
      <section name="Project.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  </startup>
  <userSettings>
    <Project.My.MySettings>
      <setting name="LastPosition" serializeAs="String">
        <value>-1, -1</value>
      </setting>
      <setting name="LastSize" serializeAs="String">
        <value>-1, -1</value>
      </setting>
    </Project.My.MySettings>
  </userSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
      </dependentAssembly>
    </assemblyBinding>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

我清理/重建了项目并重试,但它仍然给出相同的错误,当我查看文件时,绑定重定向仍然存在。My Project.exe.config

因此,我将推荐的 XML 元素添加到文件中:.vbproj

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{7BBF4599-D28D-4E03-B6D6-FC40C051263B}</ProjectGuid>
    <OutputType>WinExe</OutputType>
    <StartupObject>Project.My.MyApplication</StartupObject>
    <RootNamespace>Project</RootNamespace>
    <AssemblyName>My Application</AssemblyName>
    <FileAlignment>512</FileAlignment>
    <MyType>WindowsForms</MyType>
    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>

<!-- VERIFIED PER STACKOVERFLOW ANSWER 43996389 -->
    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

<!-- ADDED PER STACKOVERFLOW ANSWER 43996389 -->
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>

    <Deterministic>true</Deterministic>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>x64</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <DefineDebug>true</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <OutputPath>bin\Debug\</OutputPath>
    <DocumentationFile>My Application.xml</DocumentationFile>
    <NoWarn>
    </NoWarn>
    <WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugType>pdbonly</DebugType>
    <DefineDebug>false</DefineDebug>
    <DefineTrace>true</DefineTrace>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <DocumentationFile>My Application.xml</DocumentationFile>
    <NoWarn>
    </NoWarn>
    <WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors>
  </PropertyGroup>
  <PropertyGroup>
    <OptionExplicit>On</OptionExplicit>
  </PropertyGroup>
  <PropertyGroup>
    <OptionCompare>Binary</OptionCompare>
  </PropertyGroup>
  <PropertyGroup>
    <OptionStrict>On</OptionStrict>
  </PropertyGroup>
  <PropertyGroup>
    <OptionInfer>On</OptionInfer>
  </PropertyGroup>

我验证了该元素已经存在,所以我只是添加了该元素。我再次尝试运行该解决方案,但在同一行代码中遇到了相同的异常。AutoGenerateBindingRedirectsGenerateBindingRedirectsOutputType

然后,我还在同一问题的另一个答案中找到了删除所有 bin/obj 文件夹的建议,所以我这样做了,然后再试一次。我仍然收到相同的错误,并且绑定重定向已再次添加到文件中。My Project.exe.config

实际上,我发现的有关引用错误版本的程序集的所有其他问题似乎都涉及同一项目中的程序集,并且仅指向将适当的绑定重定向添加到(或)文件。app.configweb.config

只是为了看看它是否会有所作为,我继续将整个元素组从我的类库项目复制到我的 Windows 窗体应用程序项目中,以强制程序集绑定重定向按预期发生。不幸的是,当我在IDE中再次尝试时,我仍然遇到相同的错误。<runtime>app.configApp.config

如上所述,引发异常的特定代码行只是尝试实例化一个新对象(我已经验证了该属性不是 NULL):NpgsqlConnectionMe.ConnectionString

    PGConnection = New NpgsqlConnection(Me.ConnectionString)

此代码实际上位于库项目中(因此,我不必在使用同一库的所有项目中引用 Npgsql),因此我认为它应该使用该项目在运行时引用的程序集。

整个事情中最奇怪的部分是,我在另一个 Windows 窗体应用程序项目中引用了这个完全相同的类库项目,并且它似乎没有任何错误。我不知道为什么Visual Studio总是使用错误的程序集引用生成此应用程序的文件,并且我不知道如何阻止它这样做。有人可以给我指出正确的方向吗?如果您需要任何其他信息来帮助诊断或解决问题,我很乐意提供我所能提供的一切。exe.config


更多疑难解答

我创建了一个全新的解决方案,从一个新的 Windows 窗体应用程序项目开始,并再次引用相同的类库项目:

New Solution Referencing Class Library project

设置完成后,我尝试运行它并再次出现相同的错误。只是为了测试,我进入了 Windows 窗体应用程序项目的属性,并打开了“自动生成绑定重定向”选项。当我尝试实例化一个新对象时,再次运行解决方案会引发相同的异常。NpgsqlConnection

为了解决有关将程序集降级回 6.0.0 的评论,我在故障排除中尝试过,但这只会导致处理库中其他依赖项的其他错误。有一次,我什至试图将库降级到 6.x 版本,看看我是否可以让它以这种方式工作,但这最终导致了一堆其他编译器错误(尽管我不记得具体是什么)。Npgsql

I guess the simplest form of my question at this time is, "How do I get the Windows Forms Application project to stop automatically trying to load the 6.0.0 version of ?" Of course, I'd like to know why it's trying in the first place so that I can prevent it from happening in the future, but I just need to get myself out of this "DLL Hell".Microsoft.Extensions.Logging.Abstractions

I considered asking the Npgsql developers about this, but the issue definitely seems to be more related to something the Visual Studio is doing as opposed to anything the library has any sort of control over. Am I missing something obvious here?


UPDATE - WORKAROUND "FIX"

So, I finally broke down and went to the NuGet pakage manager for the Windows Forms Application project and had it install the 7.0.0 version of there (in addition to having it installed in my Class Library project). NuGet, of course, installed a few other dependencies as well (that are, again, already included in the Class Library project).Microsoft.Extensions.Logging.Abstractions

This seems to have "resolved" this specific issue in that I no longer receive the exception when I try to instantiate a new object. It does not, however, answer the question about why the Windows Forms Application project is automatically generating its own binding redirect for that library and totally overriding/ignoring the specific definition I've set in the Class Library project. Also, I've been actively trying to avoid adding packages/references in the Windows Forms Application project that aren't explicitly needed by that project itself - especially those that are already in the Class Library project like this one.NpgsqlConnection

Additionally, after "resolving" that assembly reference issue, I also encountered another issue with opening the connection that had to do with a similar assembly problem - this time with - so I went ahead and added that reference to my Windows Forms Application project as well. Now it all seems to be running without error but, IMO, there needs to be a way to explicitly prevent the project from trying to load specific assemblies that aren't absolutely required. To that end, I'm leaving this question open for any insight.System.Text.Json

vb.net visual-studio-2022 npgsql 项目和解决方案 程序集绑定重定向

评论

0赞 Hans Passant 2/24/2023
It is not obvious why you want the 7.0.0 Nuget package. Npgsql is only happy with 6.0.0.0 and insists on getting it. Resistance is futile.
0赞 G_Hosa_Phat 2/24/2023
@HansPassant - Actually, I believe I tried to downgrade to the 6.0 version but had issues with other dependencies in the project. Besides, I can't stand seeing that little number to the side of the Updates section of the NuGet Package Manager in VS. ;)

答: 暂无答案