Getting Started with Microservices in C# and .NET

Here's a detailed introductory post on Getting Started with Microservices in C# and .NET, ideal for developers looking to transition from monolithic applications or start fresh with a microservices architecture. We’ll explore the fundamentals of microservices, why you might choose them, and how to get started building them using C# and .NET.

Getting Started with Microservices in C# and .NET

Getting Started

Microservices have become a popular architectural pattern for building scalable, maintainable, and independently deployable applications. If you're a C# developer working with the .NET ecosystem, you're in luck. .NET provides a robust set of tools and libraries to help you build and manage microservices efficiently.

What Are Microservices?

Microservices are a software architecture style where applications are structured as a collection of small, independent services. Each service is self-contained, implements a single business capability, and communicates with other services via lightweight mechanisms (typically HTTP/REST, gRPC, or messaging queues).

Key Features:
  • Independently deployable
  • Loosely coupled
  • Organized around business capabilities
  • Owned by small, autonomous teams

Why Microservices?

.NET, especially with .NET Core and .NET 6/7/8, is a powerful platform for building microservices. Here’s why:
  • Cross-platform: Run on Windows, Linux, or macOS.
  • High performance: Especially with ASP.NET Core.
  • Built-in support:for Web APIs, gRPC, messaging, and dependency injection.
  • Excellent toolingwith Visual Studio, CLI, and Docker integration.
  • Strong ecosystem: Includes Entity Framework Core, Dapper, SignalR, Polly, Serilog, etc.

Createing a Microservice in C# and .Net

We'll build a simple product catalog microservice using ASP.NET Core Web API.
Prerequisites
  • .NET 8 SDK
  • Visual Studio 2022+ or VS Code
  • Basic knowledge of C# and REST APIs

Create the Project
  1. Open Visual Studio
  2. Click Create a new project
  3. Select ASP.NET Core Web API
  4. Click Next
  5. Name your project (e.g., MyWebApi)
  6. Choose .NET 6 or later (recommend .NET 8 if available)
  7. Click Create

Define a Model
In Solution Explorer:
  1. Right-click the project.
  2. Choose Add > New Folder.
  3. Name the folder Models.
  4. Right-click the Models folder.
  5. Select Add > Class.
  6. Name it (e.g., Product.cs).
  7. Click Add.
  8. Update your model class with this code.

public class Product
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public decimal Price { get; set; }
}

Create a Repository
Interface: IProductRepository.cs
public interface IProductRepository
{
  IEnumerable<Product> GetAll();
  Product? GetById(Guid id);
  void Add(Product product);
}

Class: InMemoryProductRepository.cs
public class InMemoryProductRepository : IProductRepository
{
  private readonly List<Product> _products = new();
  public IEnumerable<Product> GetAll() => _products;
  public Product? GetById(Guid id) => _products.FirstOrDefault(p => p.Id == id);
  public void Add(Product product)
  {
    product.Id = Guid.NewGuid();
    _products.Add(product);
  }
}

Register Repository as Services
Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddSingleton<IProductRepository, InMemoryProductRepository>();
var app = builder.Build();
app.MapControllers();
app.Run();

Create the API Controller
In Solution Explorer:
  1. Right-click the project.
  2. Choose Add > New Folder.
  3. Name the folder Controllers.
  4. Right-click the Controllers folder.
  5. Select Add > Class.
  6. Name it (e.g., ProductsController.cs).
  7. Click Add.
  8. Update your ProductsController with this code.

// Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
  private readonly IProductRepository _repo;
  public ProductsController(IProductRepository repo)
  {
    _repo = repo;
  }
  [HttpGet]
  public IActionResult GetAll() => Ok(_repo.GetAll());
  [HttpGet("{id}")]
  public IActionResult GetById(Guid id)
  {
    var product = _repo.GetById(id);
    return product is not null ? Ok(product) : NotFound();
  }
  [HttpPost]
  public IActionResult Create(Product product)
  {
    _repo.Add(product);
    return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
  }
}

Testing the API
Run your project. Once running, try the following endpoints using tools like Postman, curl, or httpie for testing.
  • GET /api/products – list all products
  • POST /api/products – create a new product
  • GET /api/products/{id} – get product by ID

Summary

Microservices offer significant improvements in scalability, resilience, and agility for your applications. Using .NET, you can build efficient, high-performance microservices that fit naturally into modern cloud-native architectures. Begin with a small scope, targeting individual business functions, and gradually expand your system over time.

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال