Mirror site is read only www.netnr.com
netnr 2023-02-13 21:20:01 2023-07-29 01:53:47 👁384 💬0

引言

使用 Native AOT 发布应用程序会创建一个完全独立的应用程序版本,不需要运行时(所有内容都包含在一个文件中)。

.NET 7 中引入了作为 Native AOT 发布的选项,在 .NET 8 中持续改进

Native AOT 发布的 Hello World 应用程序大小:

OS .NET 7 .NET 8 Preview
Linux x64 (with -p:StripSymbols=true) 3.76 MB 1.84 MB
Windows x64 2.85 MB 1.77 MB

准备

Windows 需安装 VS2022 和 C++ 桌面开发

Ubuntu (18.04+) 需安装 sudo apt-get install clang zlib1g-dev

Alpine (3.15+) 需安装 sudo apk add clang build-base zlib-dev

添加该属性到项目文件

<PropertyGroup>
    <PublishAot>true</PublishAot>
</PropertyGroup>

发布

dotnet publish -r win-x64 -c Release

dotnet publish -r linux-arm64 -c Release

局限性

  • 没有动态加载(如 Assembly.LoadFile)
  • 没有运行时代码生成(如 System.Reflection.Emit)
  • 无 C++/CLI
  • 无内置 COM(仅适用于 Windows)
  • 意味着编译成一个已知不兼容的文件
  • .NET 7 仅支持控制台(console)应用程序,不支持 ASP.NET Core
  • .NET 7 仅支持 win-x64、win-arm64、linux-x64、linux-arm64

实践

没安装 C++ 会报错

Microsoft.NETCore.Native.Windows.targets(116,5): error : 
Platform linker not found. To fix this problem,
Make sure to install the Desktop Development for C++ workload.
For ARM64 development also install C++ ARM64 build tools.

在 Windows 发布 Linux 会提示不支持

Microsoft.NETCore.Native.Publish.targets(58,5): error : 
Cross-OS native compilation is not supported.

.NET 8 跟进:
https://github.com/dotnet/runtime/issues/69739
https://github.com/dotnet/aspnetcore/issues/47240
https://github.com/dotnet/core/issues/8133

Native AOT:
https://learn.microsoft.com/zh-cn/dotnet/core/deploying/native-aot/


链接