.NET Core Microservices

Overview

Microservices are an architectural style that structures an application as a collection of loosely coupled services. .NET Core provides a robust, cross‑platform foundation for building, deploying, and scaling microservice‑based systems.

This documentation guides you through best practices, patterns, and tools to create production‑ready microservices using .NET Core.

Recommended Architecture

The typical .NET Core microservice stack includes:

  • API Gateway (Ocelot, YARP)
  • Service Discovery (Consul, Eureka)
  • Message Bus (RabbitMQ, Azure Service Bus)
  • Containerization (Docker, Kubernetes)
  • Observability (OpenTelemetry, Prometheus, Grafana)
// Example: Minimal API for a product service
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

app.MapGet("/api/products", () => ProductsRepository.GetAll())
   .WithName("GetAllProducts")
   .Produces<IEnumerable<Product>>();

app.Run();

Service Communication

Choose the appropriate protocol based on latency, reliability, and data contracts.

PatternTypical Use‑CaseImplementation
HTTP/RESTSynchronous CRUD opsASP.NET Core Controllers or Minimal APIs
gRPCHigh‑performance inter‑service callsGrpc.AspNetCore
Message QueuesEvent‑driven workflowsMassTransit, Rebus

Deployment Strategies

Containerize each microservice and orchestrate with Kubernetes or Azure Container Apps.

# Dockerfile for a .NET Core microservice
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 ["MyService/MyService.csproj", "MyService/"]
RUN dotnet restore "MyService/MyService.csproj"
COPY . .
WORKDIR "/src/MyService"
RUN dotnet build "MyService.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "MyService.csproj" -c Release -o /app/publish

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

Monitoring & Logging

Integrate OpenTelemetry SDK for distributed tracing and use Serilog for structured logging.

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console()
    .WriteTo.Elasticsearch(new ElasticsearchSinkOptions(new Uri("http://es:9200"))
    {
        AutoRegisterTemplate = true,
        IndexFormat = "microservice-logs-{0:yyyy.MM.dd}"
    }));
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddJaegerExporter());

Sample Projects