.NET 6 Upgrade of OnionAPI: A Template for Clean Architecture
Written on
Introduction
I am excited to share the launch of OnionAPI version 1.5, now compatible with Visual Studio 2022 and .NET 6. This guide outlines how to install and utilize the template to quickly set up an ASP.NET WebAPI project. The template features advanced functionalities, including pagination, filtering, sorting, and CRUD operations, all structured according to Clean Architecture for enhanced scalability and maintainability.
OnionAPI Template Overview
According to Fuji Nguyen, the author of the OnionAPI template, "The OnionAPI template is a blueprint for developing sophisticated REST APIs. It can save developers at least 40 hours compared to starting a REST API project from the ground up."
What is a Visual Studio Template?
A Visual Studio template supplies the essential files for a specific project type, including standard assembly references, default project properties, and compiler settings. Visual Studio comes pre-installed with numerous project templates, such as the ASP.NET Web Application and Class Library templates, which you can select when initiating a new project.
What is the OnionAPI Template?
The OnionAPI template enables developers to scaffold an ASP.NET Core REST API project following a clean architecture approach (illustrated in Figure 1).
After specifying the project name, the template generates five projects within the Visual Studio solution, each prefixed with the project name and organized with appropriate namespaces in the source code. The five projects include:
- Domain — containing entities and common models
- Application — encompassing interfaces, CQRS features, exceptions, and behaviors
- Infrastructure.Persistence — data access API leveraging Entity Framework
- Infrastructure.Shared — housing common services like Mail Service and DateTime Service
- WebApi — for API controllers to expose REST API resources and endpoints
Figure 2 showcases the source code organization scaffolded by the OnionAPI template for the sample project MyOnionApi. It illustrates the grouping of five projects into three folders: Core, Infrastructure, and Presentation, aligned with the layers outlined in the Clean Architecture pattern.
The solution's technology stack promotes a loosely-coupled and inverted-dependency architecture, employing sound design patterns and practices:
- ASP.NET CORE 6 — a framework for building RESTful services, often referred to as web APIs, using C#
- Repository Pattern — serves as an abstraction layer between the data access layer and the controller
- CQRS (Command and Query Responsibility Segregation) Pattern — separates read and write operations for a data store to enhance performance, scalability, and security
- Entity Framework Core — a lightweight, extensible, open-source, cross-platform variant of the widely-used Entity Framework data access technology
- Swashbuckle — easily integrates Swagger into WebApi projects, blending ApiExplorer and Swagger/swagger-ui for a rich API discovery and documentation experience
- Bogus — a .NET library providing realistic mock data for rapid REST API design and testing
Prerequisites
- Latest .NET Core 6 SDK
- Visual Studio 2022 Community — a free C# code editor
Tutorial Content
The tutorial is structured into three parts:
- Download and install the OnionAPI template from Visual Studio Marketplace
- Scaffold a new API project using the OnionAPI template
- Explore Filtering, Sorting, Paging, and Shaping features
Part 1 — Download and Install OnionAPI Template
You can acquire the OnionAPI template from the Visual Studio Marketplace, as depicted in Figure 3. As of this writing, the template has been downloaded 975 times by developers.
After downloading, click on the VSIXTemplateOnionAPI.vsix file to install the extension. For those unfamiliar with Visual Studio Extensions, refer to the Manage Extensions for Visual Studio for installation guidance.
Part 2 — Scaffold a New REST API Project with OnionAPI Template
The simplest method to create a new project is by starting from a template tailored for a specific application type. A project template includes a foundational set of pre-generated code files, configuration files, assets, and settings.
Upon opening Visual Studio, the start window appears, where you can opt to create a new project, as shown in Figure 4.
If Visual Studio is already open, you can create a new project by selecting File > New > Project from the menu bar, as illustrated in Figure 5, or by clicking the New Project button on the toolbar.
Task 1 — Select a Template Type
On the "Create a new project" page, a list of your recently used templates will be displayed on the left, arranged by most recently used.
If you are not selecting from the recent templates, you can filter all available project templates by entering search terms in the search box, such as "OnionAPI."
Task 2 — Create a Solution
On the "Create a new project" screen, search for and select the OnionAPI template, then click the Next button. Visual aid can be found in Figure 6.
Enter the project name (e.g., MyOnionAPI) and click the Create button, as shown in Figure 7.
Press F5 to run the project. Swagger should display in the browser, as illustrated in Figure 8.
Part 3 — Exploring Filtering, Sorting, Paging, and Shaping Features
The OnionAPI template generates two REST resources:
- Employees — A mock REST API resource where data is dynamically created using the Bogus library at runtime. For more information about Bogus, refer to the Related Stories section later in this guide.
- Positions — This REST API resource retrieves its data from the actual database table, Positions. When the project runs for the first time, this table is automatically populated with 1,000 rows of dummy data.
To test the REST API in Swagger (refer to Figure 9 for visual guidance):
- Click on Employees > GET to expand the view.
- Click on Try it out.
- Enter parameters (leave blank for defaults).
- Click on the Execute button.
- Review the JSON output.
Figure 10 illustrates a sample screenshot of the JSON output. For performance, server-side paging is utilized. The response body contains a "wrapper" with user-friendly data for frontend applications.
- pageNumber — pagination index (e.g., 1, 2, 3). Default is page 1.
- pageSize — number of records per page. Default is 10.
- recordsFiltered — count of records matching the search criteria. For this example, the criteria is "Chief."
- recordsTotal — total number of employee records in the database.
- succeeded — boolean indicating the status of the web API response.
- message — user-friendly error message, if applicable.
- errors — system error, if any.
- data — JSON response data.
The data response comprises eleven columns. If you want to reduce the response to fewer columns to lessen the data sent over the network, you can specify the required columns. For instance, if the frontend app only needs firstName, lastName, and employeeTitle, input these column names in the Fields parameter as shown in Figure 11, and the JSON response will include only those three columns in the "Data" section, as shown in Figure 12. Additional tutorials on Pagination can be found in the References section.
The scaffolded source code also includes example methods for data modification within the Positions resource. As illustrated in Figure 13, methods such as POST, GET, PUT, and DELETE are available to facilitate CRUD operations.
Source Code
For reference, the scaffolded source code project can be found at workcontrolgit/MyOnionApi (github.com). You can fork and run it using Visual Studio 2022 without any changes.
References
Here are some technical resources on software patterns and related blogs covering pagination, CRUD, etc.:
- Common web application architectures — A Microsoft publication detailing common application patterns. Refer to the Clean Architecture section.
- CAT architecture pattern for modern app SPA/Mobile — A blog discussing modern app architecture based on service separation.
- Bogus Library for Fake Data In ASP.NET Core WebAPI — A blog focused on using Bogus library in Web API projects.
- NetCore REST API/Dapper/SQLKata with VS Template KissApi — Explore the KissAPI template if you prefer Dapper over EntityFramework.
- NetCore 5 Pagination 100,000+ Rows — A blog tutorial on implementing pagination using Angular as a SPA and .NET CORE as backend WebAPI.
- Angular 11 CRUD with .Net 5 REST API Tutorial — A blog tutorial on implementing CRUD using Angular as a SPA and .NET CORE as backend WebAPI.
Summary
Many organizations face challenges in managing development governance and seek process improvement tools that add value. The OnionAPI template enhances consistency while reducing delivery time.
The OnionAPI provides boilerplate code for creating advanced REST API features, including data filtering, sorting, shaping, paging, and CRUD operations. These features are designed as base classes, allowing you to inherit and extend them to suit your project's specific needs.
Let’s peel the onion!