.NET Core  

🧩 Building Microservices with C# and .NET Core β€” A Complete Guide with Example

🌟 Introduction

In the modern software world, microservices architecture has become a popular choice for building scalable , maintainable , and independent applications. Instead of creating a single large monolithic application, microservices split the system into smaller, self-contained services that communicate through APIs.

.NET Core (now .NET 8) provides an excellent platform for developing microservices due to its cross-platform support, high performance, and built-in API development tools.

πŸš€ What Are Microservices?

Microservices are small, independent services that:

  • Have their own database and business logic.

  • Communicate via HTTP/REST APIs or message queues (RabbitMQ, Kafka).

  • Can be deployed, scaled, and updated independently.

πŸ—οΈ Microservice Architecture Overview

A simple microservice system might include:

  
    +---------------------------+
|   API Gateway (Ocelot)    |
+---------------------------+
          |
          ↓
+---------------------------+     +----------------------------+
|  Product Microservice     |     |  Order Microservice        |
|  (.NET Core Web API)      |     |  (.NET Core Web API)       |
+---------------------------+     +----------------------------+
          |                                 |
          ↓                                 ↓
+---------------------------+     +----------------------------+
|  SQL Server Database      |     |  MongoDB / PostgreSQL DB   |
+---------------------------+     +----------------------------+
  

🧠 Key Benefits of Using Microservices in .NET Core

  • βœ… Scalability: Scale services independently.

  • βœ… Faster Development: Teams can work on separate services in parallel.

  • βœ… Technology Freedom: Each microservice can use different tech stacks.

  • βœ… Easy Maintenance: Smaller codebases are easier to debug and update.

βš™οΈ Example: Building a Simple Product Microservice in .NET Core

Let’s build a small Product Microservice using .NET 8 Web API.

Step 1. Create the Project

  
    dotnet new webapi -n ProductService
cd ProductService
  

Step 2. Define the Product Model

  
    namespace ProductService.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}
  

Step 3. Create the Repository

  
    using ProductService.Models;
using System.Collections.Generic;

namespace ProductService.Repository
{
    public class ProductRepository
    {
        private static readonly List<Product> _products = new()
        {
            new Product { Id = 1, Name = "Laptop", Price = 55000 },
            new Product { Id = 2, Name = "Mobile", Price = 18000 }
        };

        public IEnumerable<Product> GetAll() => _products;

        public Product GetById(int id) => _products.Find(p => p.Id == id);

        public void Add(Product product)
        {
            product.Id = _products.Count + 1;
            _products.Add(product);
        }
    }
}
  

Step 4. Create the Controller

  
    using Microsoft.AspNetCore.Mvc;
using ProductService.Models;
using ProductService.Repository;

namespace ProductService.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProductController : ControllerBase
    {
        private readonly ProductRepository _repo = new();

        [HttpGet]
        public IActionResult Get() => Ok(_repo.GetAll());

        [HttpGet("{id}")]
        public IActionResult GetById(int id)
        {
            var product = _repo.GetById(id);
            return product == null ? NotFound() : Ok(product);
        }

        [HttpPost]
        public IActionResult Post(Product product)
        {
            _repo.Add(product);
            return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
        }
    }
}
  

Step 5. Run the Microservice

  
    dotnet run
  

Visit:
πŸ‘‰ https://localhost:5001/api/product

You’ll see a JSON response like

  
    [
  { "id": 1, "name": "Laptop", "price": 55000 },
  { "id": 2, "name": "Mobile", "price": 18000 }
]
  

🌐 Step 6. Connect with API Gateway (Optional)

You can manage multiple microservices using Ocelot API Gateway :

  
    dotnet add package Ocelot
  

Then create a configuration file ( ocelot.json ) and define routes for all microservices.

🧩 Step 7. Add Communication Between Microservices

Microservices communicate via:

  • RESTful APIs ( HttpClient , Refit )

  • Message Brokers like RabbitMQ, Kafka, or Azure Service Bus

Example using HttpClient

  
    var client = new HttpClient();
var response = await client.GetAsync("https://localhost:5002/api/order");
var data = await response.Content.ReadAsStringAsync();
  

πŸ§ͺ Step 8. Dockerize the Microservice

Create a Dockerfile

  
    FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "ProductService.dll"]
  

Then build and run:

  
    docker build -t productservice .
docker run -p 8080:80 productservice
  

πŸ“¦ Advanced Topics

  1. Service Discovery: Use Consul or Eureka.

  2. Logging & Monitoring: Use Serilog , Elastic Stack , or Application Insights .

  3. Authentication: Implement JWT across microservices.

  4. Database Per Service: Each microservice should manage its own data store.

🧾 Conclusion

Microservices in .NET Core enable modular, scalable, and high-performing applications.
With proper use of API Gateway, containerization, and service communication, you can build robust distributed systems.

Whether you’re developing a large enterprise solution or transitioning from monolithic architecture, .NET Core microservices offer the flexibility and tools to make your system future-ready.