• Bits & Bytes
  • Posts
  • Vertical Slices: Building Scalable .NET Core Microservices

Vertical Slices: Building Scalable .NET Core Microservices

Vertical Slices Architecture

To create a .NET Core Web API microservice project using Vertical Slice Architecture, with Product and Customer entities (where a Customer has a list of Products), and set up Entity Framework Core with an in-memory database, follow these steps:

Step 1: Create the .NET Core Web API Project

Open a terminal or command prompt. Run the following command to create a new .NET Core Web API project:

dotnet new webapi -n ProductCustomerMicroservice
cd ProductCustomerMicroservice

Step 2: Add Required NuGet Packages

Add the following NuGet packages to your project:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.InMemo

Project Folder Structure

Step 3: Define the Entity Classes

Create the Product and Customer entity classes.

Create a folder named Entities. Add the Product class:

Add the Customer class:

Step 4: Set Up Entity Framework Core

Create a folder named Data. Add a DbContext class:

Register the DbContext in Program.cs😀

Step 5: Implement Vertical Slice Architecture

Vertical Slice Architecture organizes code around features rather than layers. Each feature will have its own folder containing all the necessary files (e.g., handlers, requests, responses).

  1. Create a folder named Features.

  2. Inside Features, create subfolders for each feature, such as Customers and Products.

Step 6: Implement CRUD Operations

Customer Feature

  1. Create a folder Features/Customers.

  2. Add a CreateCustomer feature:

  3. Create a CreateCustomerCommand.cs

  1. Create a CreateCustomerHandler.cs

  1. Add an Endpoint’s

  1. Add a GetCustomerById feature:

  2. Create a GetCustomerByIdQuery.cs

  1. Create a GetCustomerByIdHandler.cs😀 

  1. Add an Endpoint's

Step 7: Test the API

  1. Run the application:

dotnet run
  1. Use tools like Postman or Swagger UI to test the endpoints:

    • Create a customer: POST /api/customers

    • Get a customer by ID: GET /api/customers/{id}

Step 8: Repeat for Product Feature

Follow a similar pattern to implement CRUD operations for the Product entity.

This setup provides a clean, maintainable structure using Vertical Slice Architecture and Entity Framework Core with an in-memory database. You can expand it further by adding more features and validation.

For a closer look at the code and to explore the full project, visit our GitHub repository!

Reply

or to participate.