Как разрешить конфликты версий пакета .NET Core - программирование

Как разрешить конфликты версий пакета .NET Core

Я перехожу из веб-приложения .NET MVC 5 в проект веб-API.NET Core 2.2 вместе с пятью проектами .NET Standard 2.0, которые размещены в одном решении.

Сейчас я получаю 28 предупреждений (MSB3277) о конфликтах пакетов, которые находятся в пространстве имен System. Например, кажется, что существует конфликт версий для System.Collections.Concurrent между Version=4.0.11.0 и Version=4.0.14.0 (см. Блок ошибок ниже).

Попытка устранения неисправности:

  1. Я попытался удалить все .NET Core SDK, которые я не использую, и в настоящее время установлен 2.2.300. Это не сработало.
  2. Я попытался зайти в NuGet на уровне решения, чтобы установить недостающую сборку, но 4.0.14 даже не доступен в списке выбора. Я могу выбрать 4.0.12 из следующих версий: 4.3, 4.0.12, 4.0.10 и 4.0.0. Я попытался установить 4.3 во всех проектах, но это не сработало.
  3. Другие решения в Интернете, по-видимому, рекомендуют либо загрузить версию из SDK, либо жестко кодировать ссылку в файле *.csproj, чего я не предпочитаю делать, если в этом нет необходимости. Мне не нравится первый, потому что кажется нелогичным движение назад, и мне не нравится последний, потому что это жестко кодирует исправление для постоянного использования старого пакета, что кажется действительно плохой идеей, потому что кажется маловероятным, что оно будет обновить до новых версий, которые будут выпущены.

Кто-нибудь знает, как разрешить эти предупреждения? Любая помощь очень ценится.

Подробный вывод о сборке для одного из предупреждений:

Line 5419: 3>    Dependency "System.Collections.Concurrent, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
Line 5420: 3>        Could not resolve this reference. Could not locate the assembly "System.Collections.Concurrent, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
Line 5675: 3>    There was a conflict between "System.Collections.Concurrent, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Collections.Concurrent, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
Line 5675: 3>    There was a conflict between "System.Collections.Concurrent, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" and "System.Collections.Concurrent, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
Line 5676: 3>        "System.Collections.Concurrent, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "System.Collections.Concurrent, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not.
Line 5676: 3>        "System.Collections.Concurrent, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was chosen because it was primary and "System.Collections.Concurrent, Version=4.0.14.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" was not.
Line 5677: 3>        References which depend on "System.Collections.Concurrent, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files\dotnet\sdk\NuGetFallbackFolder\netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.Concurrent.dll].
Line 5677: 3>        References which depend on "System.Collections.Concurrent, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" [C:\Program Files\dotnet\sdk\NuGetFallbackFolder\netstandard.library\2.0.3\build\netstandard2.0\ref\System.Collections.Concurrent.dll].

Обновить

Больше проблем:

https://github.com/dotnet/standard/issues/731

https://github.com/dotnet/corefx/issues/32561

Это ошибка Microsoft?

Минимальный вывод при сборке перечисляет все 28 предупреждений:

3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Collections.Concurrent" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Collections" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Collections.NonGeneric" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.ComponentModel" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Diagnostics.Debug" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Diagnostics.Process" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Diagnostics.Tracing" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.IO.FileSystem" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Linq" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Net.Primitives" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Net.Security" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Resources.ResourceManager" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Runtime" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Runtime.Extensions" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Runtime.InteropServices.RuntimeInformation" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Security.Cryptography.Algorithms" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Security.Cryptography.Csp" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Security.Cryptography.Encoding" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Security.Cryptography.Primitives" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Security.Cryptography.X509Certificates" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Text.Encoding.Extensions" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Text.RegularExpressions" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Threading" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Threading.Tasks" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Threading.ThreadPool" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Threading.Timer" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
3>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(2106,5): warning MSB3277: Found conflicts between different versions of "System.Memory" that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
4b9b3361

Ответ 1

Здесь проблема в строгом именовании и смешанных версиях сборки, по крайней мере, для "System.Collections.Concurrent", но, вероятно, для всех 28 предупреждений.

Я попытался зайти в NuGet на уровне решения, чтобы установить недостающую сборку, но 4.0.14 даже не доступен в списке выбора.

Версии, которые вы видите, являются версиями NuGet, и они не совпадают с версиями сборки. Например, версия NuGet 4.3.0-preview1-24530-04 имеет версию сборки 4.0.13.0 для стандарта .NET 1.3:

Обратите внимание, что в том же пакете версия сборки для netcore50 - 4.0.10.0!

Это ошибка Microsoft?

Нет, это особенность. Если сборка имеет строгое имя, полная версия должна совпадать. Если нет, то это даст предупреждение. Если GAC не используется, тогда может быть опубликована только одна версия сборки - так что, если используется несколько версий? Note- Все сборки Microsoft имеют строгое название.

Проблема здесь:

  • Вы включаете сборку (со строгим именем), созданную для System.Collections.Concurrent, версия 4.0.14.0.
  • Вы (косвенно) используете в сборке приложения версию 4.0.11.0 для сборки System.Collections.Concurrent.

Итак, две версии для одной сборки!

Решения

Возможны несколько решений:

  1. Везде используйте одну и ту же версию сборки для System.Collections.Concurrent (вам необходимо выяснить, какой пакет NuGet является версией сборки 4.0.14.0). Это в большинстве случаев неосуществимо.
  2. Установите версии 4.0.11.0 и 4.0.14.0 в GAC - это не очень популярный вариант в наши дни → Невозможно для .NET Core, поскольку GAC для .NET Core отсутствует. См. Есть ли эквивалент GAC для .NET Core?
  3. Используйте <bindingRedirect> в вашем .config. См. Перенаправление версий сборки | Документы Microsoft

    например, для "System.Collections.Concurrent":

    <dependentAssembly>
        <assemblyIdentity name="System.Collections.Concurrent" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="4.0.0.0-4.0.14.0" newVersion="4.0.11.0" />
    </dependentAssembly>
    

Финальные заметки

Существует 28 проблем с версиями, но есть большое изменение в том, что несколько проблем решаются с помощью одного bindingRedirect. Таким образом, лучший способ - начать с одного (предпочтительно самого верхнего уровня), перестроить и повторять, пока все не будут решены.

Также обратите внимание, что понижение сборки немного сложно, например, сборка, построенная на 4.0.13.0, может использовать функцию, которая была введена/изменена в 4.0.11. 0+. Таким образом, вы также можете обновить свою версию и использовать эту версию в атрибуте "newVersion"

Ответ 2

Переадресация привязки (bindingRedirect) для каждой сборки вы можете сделать это вручную в config или есть опция в свойствах файла Project. Проверьте это, затем обновите.

Ответ 3

Краткий ответ: при переходе с одного фреймворка на другой ВЫ МОЖЕТЕ КОПИРОВАТЬ И ВСТАВИТЬ СВОЙ КОД, НО НЕ КОПИРОВАТЬ И ВСТАВИТЬ ЗАЯВЛЕНИЯ USING НА ВЕРХ КЛАССОВ - компилятор хмурится на последнем. Это имеет смысл, потому что рассматриваемые фреймворки (от .NET Framework до .NET Core и .NET Standard) отличаются, и, не вдаваясь в подробности, Microsoft изменила положение вещей.

Юлианский ответ указал на обходной путь при копировании и вставке утверждений using. Но я решил продолжить и перенастроить проект без операторов using, а затем вручную включить их с помощью Intellisense. Все предупреждения исчезли.

Вздох, это то, что я получаю за копирование и вставку своего кода. Похоже, что усилия Microsoft по переносу .NET Framework в реализацию .NET Core и .NET Standard убедили компилятор выпить пятую часть текилы и начать говорить по-испански с разработчиками. В моем случае он сказал "es que es eso?"

Мой ответ: вы компилятор, вы должны знать.

Ответ 4

В веб-конфигах есть такой код:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>

Иногда это может вызвать проблему, с которой вы столкнулись....