How to build a microservice in ASP.NET Core

A microservices architecture can help you build applications that are flexible, scalable, and easy to maintain. Here’s how to get started with microservices in ASP.NET Core.

Stacking. Stacked building blocks.
oatawa/Shutterstock

Microservices architecture describes a collection of loosely coupled, extensible, independently deployable services that interact with each other through well-defined interfaces.

This article examines microservices architecture, its benefits and drawbacks, and then illustrates how we can implement a simple microservice in ASP.NET Core. In future articles, we’ll complete our microservices-based application by implementing an API gateway and interactions between our microservices. 

To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

What is microservices architecture?

The term microservices is used to describe a software architecture in which a large application is split into a collection of small, independently deployable, autonomous services. Each microservice is designed to accomplish a narrow set of tasks and is independently deployable and maintainable.

In other words, a microservices-based application is split into multiple small, discrete, decentralized, loosely coupled, and independently deployable services that work together as a cohesive whole.

Microservices-based applications can scale easily, and they are easier to maintain, because you can change the source code of one service of your application independently of all the others, without having to redeploy the entire application. Instead, you can redeploy only the affected service.

Benefits and drawbacks of microservices

In this section we’ll briefly examine the key benefits and drawbacks of microservices architecture. The key benefits of a microservices architecture:

  • Scalability: By allowing individual services to scale independently based on demand, microservices improve overall system scalability.
  • Agile devops: Microservices allow teams to independently develop and deploy services, allowing faster development cycles and facilitating continuous delivery and deployment aligned with devops principles and practices.
  • Fault isolation and resilience: With microservices architecture, a failure of one of the services will not affect the application in its entirety. The system is more resilient due to the isolation of faults and the ability to handle failures gracefully.
  • Technology flexibility: Microservices allow each service to use a different programming language, framework, and technology. This explains why teams can select the desired technology stack for each service when working with microservices-based applications.
  • Autonomous teams: Microservices are designed to promote small, cross-functional teams that work on individual services enabling teams to become more autonomous, efficient, and focused.

And the potential drawbacks of a microservices architecture:

  • Complexity: The distributed nature of microservices architecture introduces a higher level of complexity than its monolithic counterpart, including network latency, synchronous communication, eventual consistency, and distributed data management.
  • Operational challenges: You will require additional tools to ensure proper service discovery, monitoring, logging, and tracking because managing and monitoring multiple services in a distributed environment is challenging.
  • Increased development effort: Microservices architecture often requires a higher development effort than a monolithic architecture, due to the need to design, develop, test, and deploy multiple individual services.
  • Data management: In a distributed microservices environment, it is more difficult to maintain data consistency and transaction integrity than in a monolithic system.

Now let’s examine how we can build a simple microservices-based application in ASP.NET Core. We’ll start by creating an ASP.NET Core Web API project.

Create an ASP.NET Core Web API project in Visual Studio 2022

To create an ASP.NET Core 7 Web API project in Visual Studio 2022, follow the steps outlined below.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, leave the “Use controllers (uncheck to use minimal APIs)” box checked. We won’t be using minimal APIs in this project.
  9. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
  10. Click Create.

We’ll use this ASP.NET Core Web API project to work with the code examples in the sections below.

Implement a microservice in ASP.NET Core

For the sake of simplicity, our microservices-based application will comprise three services, namely Customer, Product, and Supplier. For brevity, I’ll create the Customer microservice here, and you can follow the same steps to create the other two microservices.

The Customer microservice will include the following types:

  • Customer – the entity class
  • ICustomerRepository – the interface for the customer repository
  • CustomerRepository – the customer repository class
  • CustomerController – an API controller that exposes one endpoint to retrieve data

To keep things simple, our microservice will have only one action method, i.e., one endpoint. To create our entity class, in the CustomerAPI project, create a file named Customer and enter the following code in there.

public class Customer
{
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
}

To create the customer repository, create an interface named ICustomerRepository in a file having the same name and enter the following code.

public interface ICustomerRepository
 {
     public Customer GetById(int id); 
 }

The CustomerRepository class implements the ICustomerRepository interface and provides an implementation of the GetById method.

public class CustomerRepository : ICustomerRepository
 {
     private readonly List<Customer> _customers;
     public CustomerRepository()
     {
         _customers = new List<Customer>
         {
             new Customer
             {
                 Id = 1,
                 FirstName = "Joydip",
                LastName = "Kanjilal",
                 Address = "Hyderabad, India"
             },
             new Customer
             {
                 Id = 2,
                 FirstName = "Steve",
                 LastName = "Smith",
                 Address = "Chicago, USA"
            }
         };
     }
     public Customer GetById(int id)
     {
         return _customers.Find(x => x.Id == id);
     }
 }

You should register an instance of type ICustomerRepository in the Program.cs file using the following piece of code.

builder.Services.AddScoped<ICustomerRepository, CustomerRepository>();

This will enable you to use dependency injection to create an instance of type ICustomerRepository in the controller class. Lastly, create a new API controller named Customer and replace the default generated code with the following code.

using Microsoft.AspNetCore.Mvc;
namespace CustomerAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class CustomerController : ControllerBase
    {
        private readonly ICustomerRepository _customerRepository;
        public CustomerController(ICustomerRepository customerRepository)
        {
            _customerRepository = customerRepository;
        }
        [HttpGet("{id}")]
        public Customer Get(int id)
        {
            return _customerRepository.GetById(id);
        }
    }
}

And that’s all you have to do to create a minimalistic microservice. When you execute the application and hit the HTTP GET endpoint of the customer microservice, the data pertaining to the customer will be displayed in your web browser.

Microservices vs. monolith

Monolithic applications consolidate all of their business functionality in a single process. As a result, change cycles of all of the various functions of the application become intertwined, and a minor change to one function might require the entire application to be rebuilt and redeployed.

With microservices architecture, the functionality of your application is broken out into many independently deployable services, enabling you to build, deploy, and manage each service separately.

In this post we illustrated how to create a simple microservice in ASP.NET Core. In the next article on microservices architecture, we’ll examine how we can use an API gateway with our microservices to enforce security and provide a single point of access to the back-end services. Then we’ll complete our microservices-based application by implementing interactions between the services.

Copyright © 2023 IDG Communications, Inc.