.NET 5 从单个文件发布中排除了一些库

.NET 5 excludes some libraries from single file publication

我在使用 .NET 5 发布单个文件可执行文件时遇到一点问题。
事实上,它并没有在可执行文件中包含所有的库,而是产生了多个文件。

在我的示例中,我使用了 SQLite 库 (Microsoft.Data.Sqlite),编译后 e_sqlite3.dll 不包括在内。
相反,在输出文件夹中,它会生成两个文件(不包括 pdb 文件):

> e_sqlite3.dll
> WpfApp1.exe

通过阅读documentation

Single-file doesn't bundle native libraries by default. On Linux, we prelink the runtime into the bundle and only application native libraries are deployed to the same directory as the single-file app. On Windows, we prelink only the hosting code and both the runtime and application native libraries are deployed to the same directory as the single-file app. This is to ensure a good debugging experience, which requires native files to be excluded from the single file. There is an option to set a flag, IncludeNativeLibrariesForSelfExtract, to include native libraries in the single file bundle, but these files will be extracted to a temporary directory in the client machine when the single file application is run.

因此(在我的例子中 e_sqlite3.dll)默认情况下不包含本机库以确保良好的调试体验
如果您无论如何都想将它们包含在应用程序可执行文件中,只需将此行添加到项目 (.csproj) 文件即可。

<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>

示例:

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

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net5.0-windows</TargetFramework>
    <UseWPF>true</UseWPF>
    <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
    <StartupObject>WpfApp1.App</StartupObject>
    <Description>WpfApp1</Description>
  </PropertyGroup>

...

</Project>