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.
| Pattern | Typical Use‑Case | Implementation |
|---|---|---|
| HTTP/REST | Synchronous CRUD ops | ASP.NET Core Controllers or Minimal APIs |
| gRPC | High‑performance inter‑service calls | Grpc.AspNetCore |
| Message Queues | Event‑driven workflows | MassTransit, 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());