Overview
Microservices are a collection of small, autonomous services that work together to build a complex application. .NET Core provides a robust platform for creating, deploying, and managing microservices.
- Lightweight and cross‑platform
- Built‑in dependency injection
- Support for containers and orchestration
Architecture
Design principles for a resilient microservice architecture:
- Domain‑driven design (DDD)
- Bounded contexts
- Event‑driven communication
- Stateless services
public class OrderService : IOrderService
{
private readonly IEventBus _eventBus;
public OrderService(IEventBus eventBus) => _eventBus = eventBus;
// ...
}
Communication
Common patterns for inter‑service communication:
- RESTful HTTP APIs (ASP.NET Core MVC)
- gRPC for high‑performance contracts
- Message queues (RabbitMQ, Azure Service Bus)
- Event sourcing and streaming (Kafka)
Data Management
Each microservice should own its data store. Recommendations:
- Relational DB: EF Core with migrations
- NoSQL: Cosmos DB, MongoDB
- Cache: Redis
services.AddDbContext<OrderContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("OrderDB")));
// Cache
services.AddStackExchangeRedisCache(opts => {
opts.Configuration = configuration["Redis:ConnectionString"];
});
Security
Secure microservices using:
- IdentityServer4 / Duende Identity Server
- JWT bearer tokens
- OAuth2 & OpenID Connect
- Transport security (HTTPS)
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
options.Authority = "https://auth.example.com/";
options.Audience = "microservice-api";
});
Deployment
Containerize services with Docker and orchestrate with Kubernetes:
# 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 ["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"]
API Reference
Explore the public API surface of the microservice framework: