Dapper.AOT 練習紀錄
Dapper, .NET8
引言
Dapper 本身是很成熟也易用的。不過它的強化套件大概都沒在積極維護的樣子。總之,到了 .NET8 因應 Native AOT 又做了重大改變。原作者之一開發了新的套件 Dapper.AOT。
關於 Dapper.AOT 關健知識
只是個編譯插件,仍需安裝 Dapper 套件。
Dapper.AOT 將置換 Dapper 內層的碼。
因為俱有 AOT 特性的關系 NET8 以上才支援。
授權方式為 Apache-2.0 處在收費與免費的疊加狀態中。
現階段有部份指令未支援,請參考 FAQ: Is every Dapper use-case supported?。
有無 AOT 的差別
無 AOT 的 Dapper 的碼用 Reflection 實作效率其實不高。加入 Dapper.AOT 編譯插件可以把碼置換成效率更高的碼。
例如下面這段碼:
const string sql = "SELECT TOP 1 * FROM MyData";
var info = conn.QueryFirst<MyData>(sql);
未導入AOT,執行時期的碼:

導入AOT後,執行時期的碼:
原本的碼被置換了。本來是 QueryFirst
置換成了 QueryFirst0
。

Dapper.AOT 安裝與設定紀錄
完整說明在此
要點整理如下。
一、安裝套件
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Dapper.AOT" Version="1.0.31" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
二、為專案加掛 DapperAot 模組
為每個可能成使用 Dapper
code 的專案(csproj)加掛 DapperAot 模組。
using Dapper;
[module: DapperAot(true)]
三、設定專案組態檔(*.csproj)
為每個可能成使用 Dapper
code 的專案(*.csproj)增加 Dapper.AOT 編譯設定 。
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- 增加 Dapper.AOT 編譯設定。將偵測並置換Dapper內層的碼 -->
<InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Dapper.AOT</InterceptorsPreviewNamespaces>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Dapper.AOT" Version="1.0.31" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
</ItemGroup>
</Project>
完成原始碼
附件 - Dapper 與相關套件現況整理
on 2024-04-25
Package Purposes:
Dapper
The core library
Dapper.Rainbow
Micro-ORM implemented on Dapper, provides CRUD helpers (readme)
Dapper.SqlBuilder
Component for building SQL queries dynamically and composably
Dapper.Contrib
強化 CRUD。官網已下架。--- 應該不再維護了吧。
Last updated