A robust, production-ready order management microservice built with ASP.NET Core 8, featuring clean architecture, PostgreSQL database, event-driven messaging, and comprehensive API capabilities.
- Clean Architecture: Separation of concerns with distinct layers (Controllers, Services, Repositories, Models)
- Entity Framework Core: PostgreSQL integration with Code First migrations
- JWT Authentication: Token-based authentication with role-based authorization
- Event-Driven Architecture: RabbitMQ and Azure Service Bus integration for order events
- Input Validation: FluentValidation for comprehensive request validation
- Error Handling: Centralized error handling middleware with standardized responses
- Pagination: Built-in pagination support for list endpoints
- API Documentation: Swagger/OpenAPI documentation with authentication
- Cross-Service Integration: MongoDB ObjectId compatibility for microservice communication
- Production Ready: Comprehensive logging, configuration management, and error handling
The Order Service uses a single-process architecture with an embedded event consumer, following industry best practices (Amazon, Netflix pattern):
OrderService.Api (REST API + Consumer)
- Publishes events via HTTP to
message-broker-service(for OrderCreated, OrderCancelled, etc.) - Consumes events directly from message broker (RabbitMQ, Kafka, or Azure Service Bus)
- Uses environment variables:
MESSAGE_BROKER_SERVICE_URL(default: http://localhost:4000) - Configuration:
MessageBrokersection in appsettings.json
Why Single Process?
- β No code duplication - Shared business logic in single deployment
- β Single database connection pool - Better resource utilization
- β Simplified deployment - One container, one process, one configuration
- β No version skew - API and consumer always in sync
- β Easier monitoring - Single process to monitor and debug
- β Better performance - No inter-process communication overhead
Embedded Consumer:
The API includes OrderStatusConsumerService as a BackgroundService that:
- Subscribes to
order.status.changedevents from Order Processor Service - Updates order status in database using the same
IOrderServiceas the API - Supports any message broker (RabbitMQ, Kafka, Azure Service Bus) via
IMessageBrokerAdapter - Runs in the same process as the REST API for optimal resource sharing
OrderService/
βββ OrderService.Api/ # REST API + Embedded Consumer
β βββ Controllers/ # REST endpoints
β βββ Consumers/ # Background consumer service
βββ OrderService.Core/ # Shared business logic
β βββ Services/ # Business logic layer
β β βββ Messaging/ # Message broker adapters
β β βββ IOrderService # Service interfaces
β βββ Repositories/ # Data access layer
β βββ Models/
β β βββ Entities/ # Domain entities
β β βββ DTOs/ # Data transfer objects
β β βββ Events/ # Event contracts
β β βββ Enums/ # Enumeration types
β βββ Data/ # EF Core context and configurations
β βββ Configuration/ # Application settings classes
β βββ Validators/ # FluentValidation validators
β βββ Middlewares/ # Custom middlewares
β βββ Extensions/ # Extension methods
βββ OrderService.Tests/ # Unit tests
- Framework: ASP.NET Core 8
- Database: PostgreSQL with Entity Framework Core
- Authentication: JWT Bearer tokens
- Validation: FluentValidation
- Messaging: RabbitMQ & Azure Service Bus
- Documentation: Swagger/OpenAPI
- Serialization: System.Text.Json
- Copy
.env.exampleto.env - Update the values in
.envwith your configuration
ConnectionStrings__DefaultConnection=Host=localhost;Database=orderservice_dev;Username=username;Password=passwordJwt__Key=your-secret-key-min-32-characters
Jwt__Issuer=OrderService
Jwt__Audience=OrderService.Users
Jwt__ExpiryInMinutes=60The Order Service supports multiple message brokers for maximum flexibility:
# RabbitMQ (default)
MessageBroker__Provider=RabbitMQ
MessageBroker__RabbitMQ__ConnectionString=amqp://guest:guest@localhost:5672/
MessageBroker__RabbitMQ__Exchange=aioutlet.events
MessageBroker__RabbitMQ__ExchangeType=topic
# Kafka (alternative)
MessageBroker__Provider=Kafka
MessageBroker__Kafka__BootstrapServers=localhost:9092
MessageBroker__Kafka__GroupId=order-service-group
# Azure Service Bus (alternative)
MessageBroker__Provider=AzureServiceBus
MessageBroker__AzureServiceBus__ConnectionString=Endpoint=sb://...
MessageBroker__AzureServiceBus__TopicName=order-eventsThe embedded consumer automatically uses the configured broker via the IMessageBrokerAdapter interface.
- .NET 8 SDK
- PostgreSQL 12+
- RabbitMQ (optional, for event publishing)
- Azure Service Bus (optional, alternative to RabbitMQ)
-
Clone the repository
git clone [repository-url] cd order-service -
Install dependencies
dotnet restore
-
Configure environment
cp .env.example .env # Edit .env with your settings -
Setup database
# Create database createdb orderservice_dev # Apply migrations dotnet ef database update
-
Run the application
dotnet run
-
Access Swagger UI
- Navigate to
https://localhost:5001/swagger
- Navigate to
| Method | Endpoint | Description | Auth Required |
|---|---|---|---|
| GET | / |
Health check and service info | No |
| GET | /api/orders |
Get paginated orders | Yes |
| POST | /api/orders |
Create new order | Yes |
| GET | /api/orders/{id} |
Get order by ID | Yes |
| PUT | /api/orders/{id}/status |
Update order status | Yes |
| GET | /api/orders/customer/{customerId} |
Get orders by customer | Yes |
| GET | /api/orders/search |
Search orders with filters | Yes |
- All endpoints (except health check) require JWT authentication
- Include
Authorization: Bearer {token}header - Roles supported:
customer,admin
The service publishes and consumes events via a configurable message broker:
- OrderCreatedEvent: Published when a new order is created
- OrderCancelledEvent: Published when an order is cancelled
- OrderUpdatedEvent: Published when order details change
- OrderStatusChangedEvent: Consumed from Order Processor Service (saga orchestrator)
- Updates order status based on saga execution results
- Reflects Payment, Inventory, and Shipping service outcomes
- RabbitMQ: Topic-based routing with configurable exchanges
- Kafka: Consumer groups with topic subscriptions
- Azure Service Bus: Topic/subscription pattern with managed identity support
- Broker-Agnostic: Switch between providers via configuration without code changes
See API_TESTING.md for comprehensive API testing examples.
{
"customerId": "507f1f77bcf86cd799439011",
"productId": "507f1f77bcf86cd799439012"
}- Use the "Debug Order Service" configuration for standard debugging
- Use "Debug Order Service (Hot Reload)" for development with automatic reloading
# Add migration
dotnet ef migrations add MigrationName
# Apply migration
dotnet ef database update
# Remove last migration
dotnet ef migrations remove- JWT token authentication
- Role-based authorization
- Input validation with FluentValidation
- SQL injection protection via EF Core
- HTTPS enforcement in production
- Structured error responses (no sensitive data exposure)
- Comprehensive logging using
ILogger - Structured logging with correlation IDs
- Error tracking and debugging support
- Performance monitoring capabilities
- Health check endpoints
ASPNETCORE_ENVIRONMENT: Environment nameConnectionStrings__DefaultConnection: Database connectionJwt__Key: JWT signing keyMessageBroker__Provider: Message broker provider
- Fork the repository
- Create a feature branch
- Commit your changes
- Push to the branch
- Create a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
For questions and support:
- Check the API Testing Guide
- Review the Swagger documentation
- Check application logs for debugging
- Create an issue for bug reports or feature requests
Built with β€οΈ using ASP.NET Core 8