DotNET 8 新特性 - AoT 编译、 MinimalAPI、Json源生成器

本文介绍了AoT编译方式在.NET8SDK中的应用,包括体积减小、性能优化、支持的特性(如gRPC和HTTP相关功能)以及如何在MinimalAPI和ORM框架(如SqlSugar)中使用,同时提及了反射技术的替代方案——源生成器。
摘要由CSDN通过智能技术生成

AoT编译方式特性

裁剪减小体积,取消JIT编译,不使用反射技术。直接产生目标机器二进制代码,目前支持x86,解决被反编译问题。

  • 使用本机 AOT 发布的应用:
  • 最大程度减少了磁盘占用空间
  • 缩短了启动时间
  • 减少了内存需求

  • | 功能 | 完全支持 | 部分支持 | 不支持 |
    | — | — | — | — |
    | gRPC | ✔️完全支持 |
    |
    |
    | 最小 API |
    | ✔️部分支持 |
    |
    | MVC |
    |
    | ❌不支持 |
    | Blazor Server |
    |
    | ❌不支持 |
    | SignalR |
    |
    | ❌不支持 |
    | JWT 身份验证 | ✔️完全支持 |
    |
    |
    | 其他身份验证 |
    |
    | ❌不支持 |
    | CORS | ✔️完全支持 |
    |
    |
    | HealthChecks | ✔️完全支持 |
    |
    |
    | HttpLogging | ✔️完全支持 |
    |
    |
    | 本地化 | ✔️完全支持 |
    |
    |
    | OutputCaching | ✔️完全支持 |
    |
    |
    | RateLimiting | ✔️完全支持 |
    |
    |
    | RequestDecompression | ✔️完全支持 |
    |
    |
    | ResponseCaching | ✔️完全支持 |
    |
    |
    | ResponseCompression | ✔️完全支持 |
    |
    |
    | Rewrite | ✔️完全支持 |
    |
    |
    | 会话 |
    |
    | ❌不支持 |
    | Spa |
    |
    | ❌不支持 |
    | StaticFiles | ✔️完全支持 |
    |
    |
    | WebSockets | ✔️ |
    |
    |

条件

  • VS 2022预览版
  • DotNET 8 SDK

创建Minimal API

使用CreateSlimBuilder()模式

var builder = WebApplication.CreateSlimBuilder();

builder.Services.AddRoutingCore().Configure<RouteOptions>(options => {
    options.SetParameterPolicy<RegexInlineRouteConstraint>("regex");
});

使用扩展方法构建OpenAPI

OpenAPI基于IEndpointRouteBuilder扩展方法创建MapGet、MapPost等来实现EndPoints

namespace Microsoft.AspNetCore.Builder
{
    //
    // 摘要:
    //     Provides extension methods for Microsoft.AspNetCore.Routing.IEndpointRouteBuilder
    //     to add endpoints.
    public static class EndpointRouteBuilderExtensions
    {
      public static RouteHandlerBuilder MapDelete(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, Delegate handler);
    ...
    }}

JSON 源生成器

在NET8的 AoT编译中不支持反射技术,对于Json序列化使用源生成器方式构建。

[JsonSerializable(typeof(WeatherForecast), GenerationMode = JsonSourceGenerationMode.Metadata)]
internal partial class MetadataOnlyWeatherForecastOnlyContext : JsonSerializerContext
{
}
builder.Services.ConfigureHttpJsonOptions(options =>
 {
     options.SerializerOptions.TypeInfoResolverChain.Insert(0, Device_ProjectJsonSerializerContext.Default);
 });

JsonSerializer.Serialize(reponse, Device_Model_Product_AssetsJsonSerializerContext.Default.APIResponseDevice_Model_Product_Assets)

最佳实践

    通过基于扩展WebApplication从而创建OpenAPI, 在Program中使用 app.MapProjectEndpoints();和builder.Services.AddTransient<ProductService>();注入Endpoint组件和Services组件来解耦。
   public static class ProductEndpoints
   {
       public static void MapProductEndpoints(this WebApplication app)
       {
           var api = app.MapGroup("/api");
           var productApi = api.MapGroup("/product").WithGroupName("产品");
           productApi.MapGet("/list", (ProductService service) =>
           {

              return Results.Text(JsonSerializer.Serialize(new APIResponse<Device_Product> { Data = service.GetProductToList() }, Device_ProductJsonSerializerContext.Default.APIResponseDevice_Product));
           });
       }
      
   }
public class ProductService
{
    public List<Device_Product> GetProductToList()
    {
        return DBContext.DB.Queryable<Device_Product>().ToList();
    }
}

ORM兼容性

  • SqlSugar、FreeSQL等三方组件均已支持AoT编译。
  • 需要额外使用rd.xml配置文件(运行时指令)指定程序元素是否适用于反射,解决AoT编译链中兼容问题
<Directives>
  <Application>
    <Assembly Name="SqlSugar"  Dynamic="Required All">
    </Assembly>
    <Assembly Name="OpenAPIServices"  Dynamic="Required All">
    </Assembly>
  </Application>
</Directives>
  • .NET 是免费的、开源的、跨平台的框架,用于构建新式应用和强大的云服务。
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zpf_37

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值