Skip to content

aioutlet/order-service

Repository files navigation

Order Service - ASP.NET Core 8 Microservice

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.

πŸš€ Features

  • 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

πŸ—οΈ Architecture

Embedded Consumer Architecture

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: MessageBroker section 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.changed events from Order Processor Service
  • Updates order status in database using the same IOrderService as 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

Project Structure

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

Technology Stack

  • 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

πŸ”§ Configuration

Environment Setup

  1. Copy .env.example to .env
  2. Update the values in .env with your configuration

Database Connection

ConnectionStrings__DefaultConnection=Host=localhost;Database=orderservice_dev;Username=username;Password=password

JWT Settings

Jwt__Key=your-secret-key-min-32-characters
Jwt__Issuer=OrderService
Jwt__Audience=OrderService.Users
Jwt__ExpiryInMinutes=60

Message Broker Configuration

The 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-events

The embedded consumer automatically uses the configured broker via the IMessageBrokerAdapter interface.

πŸš€ Getting Started

Prerequisites

  • .NET 8 SDK
  • PostgreSQL 12+
  • RabbitMQ (optional, for event publishing)
  • Azure Service Bus (optional, alternative to RabbitMQ)

Installation

  1. Clone the repository

    git clone [repository-url]
    cd order-service
  2. Install dependencies

    dotnet restore
  3. Configure environment

    cp .env.example .env
    # Edit .env with your settings
  4. Setup database

    # Create database
    createdb orderservice_dev
    
    # Apply migrations
    dotnet ef database update
  5. Run the application

    dotnet run
  6. Access Swagger UI

    • Navigate to https://localhost:5001/swagger

πŸ“‹ API Endpoints

Core Endpoints

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

Authentication

  • All endpoints (except health check) require JWT authentication
  • Include Authorization: Bearer {token} header
  • Roles supported: customer, admin

πŸ”„ Event-Driven Architecture

The service publishes and consumes events via a configurable message broker:

Events Published

  • OrderCreatedEvent: Published when a new order is created
  • OrderCancelledEvent: Published when an order is cancelled
  • OrderUpdatedEvent: Published when order details change

Events Consumed

  • OrderStatusChangedEvent: Consumed from Order Processor Service (saga orchestrator)
    • Updates order status based on saga execution results
    • Reflects Payment, Inventory, and Shipping service outcomes

Message Broker Support

  • 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

πŸ§ͺ Testing

API Testing

See API_TESTING.md for comprehensive API testing examples.

Sample Test Data

{
  "customerId": "507f1f77bcf86cd799439011",
  "productId": "507f1f77bcf86cd799439012"
}

πŸ› οΈ Development

Using VS Code Debug

  • Use the "Debug Order Service" configuration for standard debugging
  • Use "Debug Order Service (Hot Reload)" for development with automatic reloading

Database Migrations

# Add migration
dotnet ef migrations add MigrationName

# Apply migration
dotnet ef database update

# Remove last migration
dotnet ef migrations remove

πŸ”’ Security

  • 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)

πŸ“Š Monitoring & Logging

  • Comprehensive logging using ILogger
  • Structured logging with correlation IDs
  • Error tracking and debugging support
  • Performance monitoring capabilities
  • Health check endpoints

πŸš€ Deployment

Environment Variables

  • ASPNETCORE_ENVIRONMENT: Environment name
  • ConnectionStrings__DefaultConnection: Database connection
  • Jwt__Key: JWT signing key
  • MessageBroker__Provider: Message broker provider

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push to the branch
  5. Create a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

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

About

Handles customer orders from placement to tracking

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •