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
- Open Visual Studio
- Click Create a new project
- Select ASP.NET Core Web API
- Click Next
- Name your project (e.g.,
MyWebApi
) - Choose .NET 6 or later (recommend .NET 8 if available)
- Click Create
Define a Model
In Solution Explorer:- Right-click the project.
- Choose Add > New Folder.
- Name the folder Models.
- Right-click the Models folder.
- Select Add > Class.
- Name it (e.g., Product.cs).
- Click Add.
- 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.cspublic 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:- Right-click the project.
- Choose Add > New Folder.
- Name the folder Controllers.
- Right-click the Controllers folder.
- Select Add > Class.
- Name it (e.g., ProductsController.cs).
- Click Add.
- Update your ProductsController with this code.
[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 productsPOST /api/products
– create a new productGET /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