21.2 C
New York
Thursday, March 14, 2024

How you can use the REPR design sample in ASP.NET Core


Design patterns have developed to deal with issues which might be usually encountered in software program purposes. They’re options to recurring issues and complexities in software program design. We’ve mentioned many design patterns right here together with the specification sample, the unit of labor sample, the null object sample, the choices sample, the flyweight sample, the command sample, the interpreter sample, and the singleton sample.

On this put up we’ll delve into the REPR (request-endpoint-response) design sample, the way it simplifies the event of APIs, and the way it may be applied in C#.

To make use of the code examples supplied on this article, you need to have Visible Studio 2022 put in in your system. When you don’t have already got a replica, you possibly can obtain Visible Studio 2022 right here.

What’s the REPR design sample?

The REPR design sample is an method that helps builders improve code maintainability, reusability, and extensibility by isolating considerations. Builders could create well-structured and simply expandable APIs by concentrating on the request, endpoint, and response.

The REPR design sample promotes modularization and ensures a definite separation between the enter request, the logic on the endpoint, and the output response. Analogous to the vertical slice structure, the REPR design sample simplifies API improvement by organizing your APIs round endpoints as a substitute of controllers. Do not forget that the REPR design sample is neither REST-based nor resource-based. As a substitute, it’s a sample used for outlining your API endpoints.

Why use the REPR design sample?

The MVC (model-view-controller) sample has historically been used to construct API endpoints. Whereas the MVC sample does have a number of advantages, one of many main constraints of this method is bloated controllers, aka the “swollen controller drawback.” It’s because you usually find yourself with controllers having disparate strategies that aren’t cohesive (they by no means name one another) and don’t actually belong collectively. In consequence, the appliance drifts away from REST-based strategies and finally ends up with a free assortment of strategies uncovered over HTTP endpoints.

The REPR sample solves the issue of controller bloat by eliminating the necessity to have a number of motion strategies in a single controller. As a substitute, the REPR sample adheres to the one duty precept, permitting you to have one controller per motion supported in a typical use case. Different key advantages embrace the separation of considerations, improved code reusability, improved readability and maintainability, higher testability and easier debugging, and improved safety and scalability.

Nevertheless, the REPR sample additionally has sure downsides. These embrace elevated complexity and duplication of code.

Create an ASP.NET Core Net API challenge in Visible Studio 2022

To create an ASP.NET Core 8 Net API challenge in Visible Studio 2022, comply with the steps outlined beneath.

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “ASP.NET Core Net API” from the checklist of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window, specify the title and placement for the brand new challenge. Optionally examine the “Place answer and challenge in the identical listing” examine field, relying in your preferences.
  6. Click on Subsequent.
  7. Within the “Extra Data” window proven subsequent, choose “.NET 8.0 (Lengthy Time period Assist)” because the framework model and be sure that the “Use controllers” field is checked. We will likely be utilizing controllers on this challenge.
  8. Elsewhere within the “Extra Data” window, depart the “Authentication Kind” set to “None” (the default) and ensure the examine bins “Allow Open API Assist,” “Configure for HTTPS,” and “Allow Docker” stay unchecked. We received’t be utilizing any of these options right here.
  9. Click on Create.

We’ll use this ASP.NET Core Net API challenge to work with the REPR design sample within the sections beneath.

Elements of the REPR design sample

Because the title suggests, the REPR design sample contains three parts:

  1. Request: This represents the enter information that the endpoint expects. These request objects must be used for enter validation and passing information between the layers of the appliance.
  2. Endpoint: This represents the logic executed by the endpoint for a given request.
  3. Response: This represents the output information that the endpoint returns.

Create a request object

The next code snippet illustrates a typical request class.

public class CreateUserRequest
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public string Electronic mail { get; set; }
}

Equally, a request class for creating a brand new product would appear like this:

public class CreateProductRequest
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public string Class { get; set; }
    public string Description { get; set; }
    public decimal Amount { get; set; }
    public decimal Value { get; set; }
}

And a request class for retrieving product information would appear like this:

public class GetProductRequest
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public string Description { get; set; }
    public decimal Value { get; set; }
}

Implement the logic on the endpoint

Confer with the Controllers folder within the challenge you created earlier. Proper-click on the Controllers folder and create a brand new API controller named CreateProductController. Substitute the default generated code with the next code.

utilizing Microsoft.AspNetCore.Mvc;
namespace REPR_Example.ProductAPI.Endpoints.Product.CreateProduct
{
    [Route("api/[controller]")]
    [ApiController]
    public class CreateProductController : ControllerBase
    {
        [HttpPost(Name = "GetProducts")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public ActionResult GetProductsAsync(
        GetProductRequest getProductRequest)
        {
            //Write your code right here to retrieve merchandise.
            return NoContent();
        }
        [HttpPost(Name = "CreateProduct")]
        [ProducesResponseType(StatusCodes.Status204NoContent)]
        public ActionResult CreateProductAsync
        (CreateProductRequest createProductRequest)
        {
            //Write your code right here to implement logic equivalent to,
            //validation, mapping and so on.
            return NoContent();
        }
    }
}

Now, think about the next HTTP GET endpoint.

https://localhost:4586/api/getproducts

When this endpoint is hit, the everyday response in JSON will appear like this:

{
      "merchandise": [
            {
                  "id": 1,
                  "name": "HP ZBook Laptop",
                  "description": " i9 Laptop with 32 GB RAM and 1 TB SSD",
                  "price": 2500
            },
            {
                  "id": 2,
                  "name": "Lenovo Thinkpad Laptop",
                  "description": "i9 Laptop with 16 GB RAM and 1 TB SSD",
                  "price": 1500
            }
      ]
}

Create the response object

Final however not least, the next code snippet illustrates a typical response class.

public class CreateProductResponse
{
    public int StatusCode { get; set; }
    public string ErrorMessage { get; set; }
}

It must be famous right here that not all endpoints will want enter information for the request or response lessons. In lots of circumstances, chances are you’ll want solely to ship the HTTP standing code within the response.

REPR sample use circumstances

A typical use case of the REPR sample is CQRS (command and question duty segregation), the place it’s essential to have a separate endpoint for every command and question. The vertical slice structure is yet one more use case of the REPR sample, the place the appliance is cut up into vertical layers relying on their tasks.

That mentioned, you aren’t constrained to make use of REPR to construct a selected fashion of structure. You could possibly outline RESTful assets and even RPC-style endpoints utilizing the REPR design sample. You possibly can resolve to go for this sample based mostly in your software’s necessities.

The REPR design sample helps enhance the readability, maintainability, and scalability of your code base by isolating the assorted layers of your software, such because the consumer interface, the enterprise logic, and the information entry layers. You could modify and broaden the REPR sample based on your necessities by incorporating extra layers or parts.

Copyright © 2024 IDG Communications, Inc.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles