當前位置: 妍妍網 > 碼農

從REPR設計模式看 .NET的新生代類別庫FastEndpoints的威力

2024-02-09碼農

序言

又到了一年年末,春節將至,提前給各位粉絲們拜個早年,祝各位年年順風有順水,發財又發福。

這次我給大家帶來了新的API編程思路,一個新的設計模式REPR模式和FastEndpoints類別庫,希望大家評論區討論。

1. REPR設計模式

在 .NET 生態系中,特別是在使用 C# 程式語言時,REPR(Resource, Endpoint, Processor, Repository)設計模式,是一種用於構建清晰、模組化且易於維護的應用程式架構的設計模式。

REPR 設計模式將應用程式劃分為四個關鍵元件,每個元件都有其獨特的職責,從而使程式碼更具可讀性、可測試性和可延伸性。

1.1 Resource(資源)

職責: Resource 是應用程式的外部介面,負責處理外部請求和響應。在 FastEndpoints 中,可以將上文提到的 Endpoint 視為 Resource ,因為每個 Endpoint 表示應用程式對外提供的一個資源或服務。

[Route("/users")]
public classUserEndpoint
{
[HttpGet]
publicasyncTask<IActionResult>GetUsers()
{
// 外部請求處理邏輯
var users =await _userService.GetAllUsersAsync();
returnOk(users);
}
}

1.2 Endpoint(端點)

職責 Endpoint 代表應用程式的一個具體端點或資源,負責處理來自 Resource 的請求,呼叫 Processor 進行業務處理,然後返回響應。 Endpoint 在 REPR 模式中相當於控制器( Controller )的角色,但由於 FastEndpoints 框架的引入, Endpoint 更加輕量、直觀。

[Route("/users")]
public classUserEndpoint
{
[HttpGet]
publicasyncTask<IActionResult>GetUsers()
{
// 處理業務邏輯
var users =await _userService.GetAllUsersAsync();
returnOk(users);
}
}

1.3 Processor(處理器)

職責: Processor 負責處理 Endpoint 中的業務邏輯,包括數據處理、驗證、呼叫服務等。它將 Endpoint 從具體的業務細節中解耦,使得 Endpoint 只需關註請求的處理流程,而具體的業務邏輯由 Processor 完成。

public classUserProcessor
{
privatereadonlyIUserService _userService;
publicUserProcessor(IUserService userService)
{
_userService = userService;
}
publicasyncTask<IEnumerable<User>>GetAllUsersAsync()
{
// 具體的業務邏輯處理
returnawait _userService.GetAllUsersAsync();
}
}

1.4 Repository(儲存庫)

職責: Repository 負責與數據儲存互動,提供對數據的存取操作。它隱藏了底層數據儲存的細節,使 Processor Endpoint 無需關心數據的具體儲存細節,提高了系統的可維護性和擴充套件性。

public classUserRepository:IUserRepository
{
publicasyncTask<IEnumerable<User>>GetAllUsersAsync()
{
// 資料庫查詢操作
returnawait dbContext.Users.ToListAsync();
}
// 其他數據存取操作...
}

透過采用 REPR 設計模式,我們將應用程式劃分為清晰的元件,每個元件都有著獨特的職責,使得程式碼結構更加模組化和可維護。

這種模式的設計讓開發者能夠更加專註於每個元件的實作,提高了程式碼的可測試性和可讀性。

同時, REPR 模式在 FastEndpoints 的框架下得到更好的體現,使得 Endpoint 的設計更加輕松而直觀,為 .NET 開發者提供了一種優雅而高效的開發方式。

2. FastEndpoints類別庫介紹

FastEndpoints 類別庫是一款為 .NET Web API 開發而設計的創新性框架,透過引入獨特的設計理念和先進的模式,為開發者提供了更現代、直觀的開發體驗。以下是該類別庫的主要優勢對比:

  1. Endpoint 模式:

  • FastEndpoints: 引入了 Endpoint 模式,將每個端點看作一個獨立的業務單元,使程式碼更具模組化和清晰性。

  • 傳統方式: 傳統的 MVC 模式需要使用控制器,結構相對繁瑣,業務邏輯與結構耦合度高。

  • 基於特性的路由配置:

  • FastEndpoints: 使用特性直接在 Endpoint 方法上定義路由規則,簡化了路由配置,使程式碼更易維護。

  • 傳統方式: 傳統的全域路由配置檔相對繁瑣,需要額外的配置。

  • 響應式編程支持:

  • FastEndpoints: 天然支持響應式編程,透過引入 async/await 模式,處理異步操作更加方便。

  • 傳統方式: 傳統回呼方式相對冗長,巢狀的回呼函式降低了程式碼的可讀性。

  • REPR 設計模式:

  • FastEndpoints: 采用 REPR 設計模式,將應用程式劃分為 Resource、Endpoint、Processor、Repository 四個元件,提高了程式碼的可維護性和可測試性。

  • 傳統方式: 傳統 MVC 模式下缺乏清晰的元件劃分,容易造成程式碼混亂和難以維護。

  • GitHub 社群支持:

  • FastEndpoints: 在 GitHub 上托管,得到了活躍的社群支持和貢獻者的不斷改進,框架不斷演進。

  • 傳統方式: 傳統框架可能缺乏開放的社群平台,更新和改進相對較慢。

  • 透過這些優勢,FastEndpoints 類別庫為 .NET 開發者提供了更加高效、清晰、現代的 Web API 開發方式。在設計和使用上的創新使得開發者能夠更專註於業務邏輯的實作,提高了整體的開發體驗。

    3. 開啟上手模式

    3.1 安裝 FastEndpoints NuGet 包

    首先,在你的計畫中安裝 FastEndpoints NuGet 包。可以使用以下命令:

    dotnet add package FastEndpoints

    3.2 建立 Endpoint 類

    FastEndpoints 引入了 Endpoint 的概念,每個 Endpoint 都是一個處理請求的獨立單元。建立一個簡單的 Endpoint:

    usingFastEndpoints;
    public classHelloWorldEndpoint
    {
    [HttpGet("/hello")]
    publicstringHello()=>"Hello, World!";
    }

    3.3 註冊 Endpoint 到服務中

    Startup.cs 中配置服務並註冊 Endpoint:

    usingFastEndpoints;
    public classStartup
    {
    publicvoidConfigureServices(IServiceCollection services)
    {
    services.AddFastEndpoints();
    }
    publicvoidConfigure(IApplicationBuilder app)
    {
    app.UseFastEndpoints(endpoints =>
    {
    endpoints.RegisterEndpoint<HelloWorldEndpoint>();
    });
    }
    }

    3.4 模型繫結重定義

    FastEndpoints 支持自訂模型繫結方式。例如,你可以重新定義 JSON 請求的模型繫結:

    usingFastEndpoints;
    public classJsonModelBinder:IModelBinder
    {
    publicasyncTask<object?>BindModelAsync(HttpContext httpContext,Type modelType)
    {
    usingvar reader =newStreamReader(httpContext.Request.Body);
    var content =await reader.ReadToEndAsync();
    return JsonSerializer.Deserialize(content, modelType);
    }
    }
    [ModelBinder(typeof(JsonModelBinder))]
    public classCustomModel
    {
    publicstring Name {get;set;}
    }

    3.5 安全性

    FastEndpoints 提供了一些內建的安全性特性,例如授權和身份驗證。可以透過內容在 Endpoint 上定義安全性。

    usingFastEndpoints;
    [Authorize(Roles ="Admin")]
    public classAdminEndpoint
    {
    [HttpGet("/admin")]
    publicstringAdminPanel()=>"Welcome to Admin Panel!";
    }

    4 與傳統 Controller 模式對比

    - Endpoint 模式:

    更清晰的組織,每個 Endpoint 獨立,降低耦合。不需要繼承基礎類別,減少層級,提高可讀性。

    - 模型繫結重定義:

    FastEndpoints 允許更靈活的模型繫結方式,可根據需要自訂。
    Controller 模式需要在整個控制器中使用相同的繫結方式。
    - 安全性:

    FastEndpoints 內建安全性內容,可直接套用在 Endpoint 上。
    Controller 模式需要在整個控制器中使用相同的身份驗證和授權內容。

    總結

    FastEndpoints 提供了一種更現代、直觀的方式來構建 Web API,透過引入 Endpoint 模式、自訂模型繫結和內建的安全性特性,使得開發體驗更為輕松。
    與傳統的 Controller 模式相比,FastEndpoints 提供了更清晰、模組化的組織結構,降低了程式碼的耦合度。在實際計畫中,你可以根據需求選擇適合你團隊的方式。

    👓都看到這了,還在乎點個贊嗎?

    👓都點贊了,還在乎一個收藏嗎?

    👓都收藏了,還在乎一個評論嗎?