Built with the tools and technologies:
- Architecture: Built on a microservices architecture for modularity, scalability, and reliability.
- Core Modules:
- Catalog, Basket, Discount, and Ordering microservices.
- Optimized with NoSQL (DocumentDB, Redis) and relational databases (PostgreSQL, SQL Server).
- Communication:
- RabbitMQ for event-driven messaging.
- gRPC for high-speed synchronous interactions.
- Best Practices:
- Implements CQRS, DDD, and Clean Architecture for maintainability.
- Uses MediatR, FluentValidation, and MassTransit for efficient request handling.
- API Gateway:
- Managed with YARP Reverse Proxy for centralized traffic control and security.
- Containerization:
- Docker Compose ensures seamless deployment.
- Isolated environments for all services and databases.
VerticalSliceCommerceMicroservice is an e-commerce application developed using modern microservice architectures and software design patterns. This project is based on the Vertical Slice Architecture approach, which treats each functionality as an independent, self-contained slice. Unlike traditional layered architectures, each feature is developed and managed as a completed unit.
The project adopts the following modern software design patterns and approaches:
-
CQRS (Command Query Responsibility Segregation): Separates data reading (query) and writing (command) operations, improving system scalability and performance.
-
DDD (Domain-Driven Design): Developed with domain models and bounded contexts, focusing on business logic.
-
Onion Architecture: A layered structure where dependencies point inward, improving flexibility and testability.
This project aims to demonstrate how microservices can be developed modularly and independently, while also showcasing the implementation of modern software engineering practices.
Feature | Description | |
---|---|---|
⚙️ | Vertical Slice Architecture | Each functionality (feature) is treated as an independent slice. Each slice contains its own commands, queries, handlers, and API endpoints. This simplifies project growth and management. |
⚙️ | CQRS Pattern | Command and Query operations are separated. Commands manage data changes (create, update, delete), while Queries handle data reading operations. This separation improves performance and simplifies complex business logic management. |
⚙️ | Domain-Driven Design (DDD) | Business logic is centered around domain models and bounded contexts. Rich domain models are created using aggregate roots, entities, and value objects. Domain events are used to propagate system changes. |
⚙️ | Onion Architecture | A layered architecture where dependencies point inward. The Core layer contains domain models and business rules. The Infrastructure layer handles database access and communication with external services. The API layer manages HTTP endpoints and user interactions. |
⚙️ | Modular Microservice Structure | Each microservice works independently. Service communication occurs through REST APIs or message queues. This structure enhances scalability and maintainability. |
⚙️ | Testability and Flexibility | The system is made more reliable through unit and integration tests. Dependency Injection (DI) ensures easy replacement and testing of components. |
└── VerticalSliceCommerceMicroservice/
├── README.md
└── src
├── .DS_Store
├── .dockerignore
├── .idea
│ └── .idea.shop-microservice
│ └── .idea
├── ApiGateways
│ └── YarpApiGateway
│ ├── Program.cs
│ ├── Properties
│ ├── YarpApiGateway.csproj
│ ├── appsettings.Development.json
│ └── appsettings.json
├── BuildingBlocks
│ ├── BuildingBlocks
│ │ ├── Behaviors
│ │ ├── BuildingBlocks.csproj
│ │ ├── CQRS
│ │ ├── Exceptions
│ │ └── Pagination
│ └── BuildingBlocks.Messaging
│ ├── BuildingBlocks.Messaging.csproj
│ ├── Events
│ └── MassTransit
├── Services
│ ├── .DS_Store
│ ├── Basket
│ │ ├── .DS_Store
│ │ └── Basket.API
│ ├── Catalog
│ │ └── Catalog.API
│ ├── Discount
│ │ └── Discount.Grpc
│ └── Ordering
│ ├── Ordering.API
│ ├── Ordering.Application
│ ├── Ordering.Domain
│ └── Ordering.Infrastructure
├── docker-compose.dcproj
├── docker-compose.override.yml
├── docker-compose.yml
└── shop-microservice.sln
VerticalSliceCommerceMicroservice/
src
shop-microservice.sln - This file is a Visual Studio Solution (.sln) file that defines a multi-project solution
- It includes various projects with different configurations and settings, such as Debug and Release modes
- The solution also specifies dependencies between projects and provides a framework for building and deploying the entire application.docker-compose.override.yml - Defines the containerized environment for a multi-tiered e-commerce application
- It orchestrates the deployment of databases like CatalogDb, BasketDb, and OrderDb alongside essential services such as a distributed cache and a message broker
- This configuration ensures seamless communication and data management across different application components.docker-compose.yml - Defines the multi-container architecture for the e-shop application
- It specifies services like a catalog database, basket database, distributed cache, order database, and message broker, each running in its own Docker container
- The file also defines volumes to persist data across container restarts, ensuring data integrity and availability.docker-compose.dcproj - This project defines a Docker Compose configuration for the ordering API service
- It specifies the container images, ports, and dependencies required to run the API within a development environment
- The configuration allows for easy deployment and scaling of the application using Docker orchestration tools.ApiGateways
YarpApiGateway
YarpApiGateway.csproj - Defines the YarpApiGateway project, a crucial component within the overall architecture
- This project leverages the Yarp reverse proxy library to manage and route incoming API requests to appropriate backend services
- It serves as an intermediary between clients and the application's core functionalities, ensuring efficient and secure communication.appsettings.Development.json - Configures the Yarp API Gateway's behavior during development
- It defines routing rules that map incoming requests to specific microservices based on their paths, including rate limiting policies and URL transformations
- Additionally, it specifies the endpoints of each microservice cluster, allowing the gateway to connect and forward traffic appropriately.appsettings.json - The `appsettings.json` file configures the YarpApiGateway's runtime behavior
- It defines logging levels for different categories, ensuring appropriate verbosity for debugging and operational purposes
- Additionally, it specifies allowed hosts, controlling which domains can access the API gateway's services.Program.cs - This program sets up a reverse proxy API gateway within the application's architecture
- It configures rate limiting policies to control incoming requests and utilizes a configuration file to define how traffic is routed to backend services
- The gateway acts as an intermediary, handling incoming requests and forwarding them to appropriate endpoints while enforcing rate limits for security and stability.Properties
launchSettings.json - Defines the configuration settings for launching and deploying the YarpApiGateway within different environments
- It specifies application URLs, debugging options, and authentication protocols for both local development and IIS Express deployments
- These configurations ensure proper setup and functionality of the API gateway within the overall project architecture.BuildingBlocks
BuildingBlocks.Messaging
BuildingBlocks.Messaging.csproj - Defines the Building Blocks Messaging project within the larger application architecture
- This project leverages MassTransit to facilitate communication between various components using RabbitMQ as the message broker, enabling asynchronous and reliable data exchange throughout the system.Events
BasketCheckoutEvent.cs - Defines the BasketCheckoutEvent, a record representing the details of a completed basket checkout process within the application's event-driven architecture
- It encapsulates customer information, order summary, shipping and billing addresses, and payment method details, facilitating communication and processing across different system components.IntegrationEvent.cs - Defines the base structure for integration events within the application's messaging system
- This `IntegrationEvent` class provides a common template for all event types, ensuring consistency in data representation and facilitating communication between different microservices.MassTransit
Extentions.cs - This file defines an extension method that simplifies the integration of MassTransit messaging into a .NET application
- It allows developers to configure RabbitMQ as the message broker, define consumers based on provided assemblies, and set up endpoints for communication within the system.BuildingBlocks
BuildingBlocks.csproj - Defines the building blocks of the application by specifying dependencies required for core functionalities
- It leverages libraries like Mapster for object mapping, MediatR for dependency injection and command handling, FluentValidation for data validation, and Microsoft.FeatureManagement.AspNetCore for feature toggling.CQRS
IQuery.cs - Defines the interface `IQuery` which serves as a blueprint for all read operations within the application's CQRS (Command Query Responsibility Segregation) pattern
- It ensures that queries, which retrieve data without modifying it, adhere to a standardized structure and return a specific response type.IQueryHandler.cs - Defines the interface `IQueryHandler` which serves as a contract for handling queries within the application's CQRS (Command Query Responsibility Segregation) pattern
- It specifies how to process incoming queries and return corresponding responses, ensuring a clear separation of concerns between read and write operations.ICommand.cs - Defines the interface for commands within the CQRS (Command Query Responsibility Segregation) pattern
- These interfaces establish a contract for actions that modify the state of the application, ensuring they adhere to the defined structure and expectations
- This contributes to a clear separation of concerns and promotes testability within the codebase.ICommandHandler.cs - Defines the interface for handling commands within the application's CQRS architecture
- It establishes a contract for classes responsible for processing incoming commands and producing corresponding responses, ensuring consistent interaction between command dispatchers and handlers.Behaviors
LoggingBehavior.cs - The `LoggingBehavior` class enhances request handling within the application by recording detailed information about each executed request
- It logs the start and end of requests, including the type of request and response, along with the time taken to process it
- Additionally, it issues warnings if a request exceeds a specified threshold (3 seconds) for performance monitoring.ValidationBehavior.cs - The `ValidationBehavior` class ensures data integrity within the application by validating incoming requests before they reach their handlers
- It leverages FluentValidation to perform asynchronous validation against a set of defined rules, throwing a `ValidationException` if any failures occur
- This safeguards the system by preventing invalid data from being processed further.Exceptions
BadRequestException.cs - Defines a custom exception type, BadRequestException, within the BuildingBlocks module
- This exception is specifically designed to signal invalid input or requests to the application, providing additional context through a "Details" property for more informative error handling.InternalServerException.cs - Defines an `InternalServerException` class within the BuildingBlocks library
- This exception type provides a structured way to handle and communicate server-side errors, including additional details about the error context
- It ensures consistent error reporting across the application, aiding in debugging and monitoring.NotFoundException.cs - Defines a custom exception type, `NotFoundException`, specifically designed to signal when a requested entity is absent within the application's data store
- This exception provides a structured way to handle scenarios where resources are not located, improving error handling and clarity throughout the codebase.Handler
CustomExceptionHandler.cs - CustomExceptionHandler gracefully handles exceptions within the application by categorizing them and returning appropriate HTTP status codes and error messages
- It logs errors, constructs detailed problem descriptions, and sends informative responses to clients, ensuring a robust and user-friendly experience even in the face of unexpected issues.Pagination
PaginationResult.cs - The `PaginationResult` class encapsulates the results of a paginated query within the application's architecture
- It provides a structured representation of the current page index, page size, total record count, and the actual data retrieved for that specific page
- This facilitates efficient handling and display of large datasets across multiple pages.PaginationRequest.cs - Defines a data structure for handling pagination requests within the application
- The `PaginationRequest` record encapsulates the required information to determine which portion of data should be retrieved, specifying both the page index and the desired page size
- This facilitates efficient data retrieval and display across various parts of the application that require paginated results.Services
Basket
Basket.API
GlobalUsing.cs - GlobalUsing.cs establishes a shared namespace within the Basket API project
- It imports essential libraries and frameworks like Carter, MediatR, Mapster, FluentValidation, and Marten, enabling core functionalities such as routing, handling requests and events, data mapping, validation, and database interactions
- This file streamlines code organization and promotes reusability across the Basket API's components.Basket.API.http - Defines the API endpoint for retrieving a user's shopping basket
- This configuration specifies the host address and URL path used to access the basket service within the overall application architecture
- It also indicates the expected data format (application/json) for requests and responses.Basket.API.csproj - Defines the Basket API, a microservice responsible for managing shopping baskets within the system
- It leverages technologies like Marten for persistence, Carter for routing, and gRPC for communication with other services, particularly the Discount service
- The API exposes endpoints for creating, updating, and retrieving baskets, ensuring seamless integration with the broader application architecture.appsettings.Development.json - Configures the development environment for the Basket API by defining connection strings for the database and Redis cache
- It also specifies settings for message broker communication, logging levels, and the gRPC endpoint for the Discount service
- These configurations are essential for the application to function correctly during development.appsettings.json - Configures the application's environment settings
- It defines connection strings for the database and Redis cache, specifies details for message broker communication, sets logging levels, and outlines the address of the Discount gRPC service
- These configurations are essential for the Basket API to function correctly within the larger project architecture.Program.cs - The `Program.cs` file bootstraps the Basket API application, configuring services and middleware necessary for its operation
- It sets up APIs, database connections, message brokers, health checks, and CORS policies to enable communication with other parts of the system and external clients.Models
ShoppingCart.cs - The `ShoppingCart` class represents a user's shopping cart within the e-commerce application
- It stores a list of items along with their quantities and prices, allowing calculation of the total price
- This class facilitates the management of individual shopping carts for each user interacting with the system.ShoppingCartItem.cs - The `ShoppingCartItem` class defines the structure of individual items within a shopping cart
- It encapsulates essential information about each product, including quantity, color, price, unique identifier, and name
- This data is crucial for managing and processing shopping carts within the e-commerce application.Properties
launchSettings.json - Defines the configuration settings for launching and debugging the Basket API application within different environments
- It specifies URLs, ports, authentication methods, and environment variables to ensure proper execution and integration with tools like IIS Express.Data
CachedBasketRepository.cs - CachedBasketRepository provides a layer of caching on top of the core Basket repository
- It retrieves and stores shopping cart data from both the underlying database and an in-memory cache, improving performance by serving frequently accessed carts directly from the cache.BasketRepository.cs - The `BasketRepository` class manages the persistence of shopping carts within the application's data store
- It provides methods to retrieve, store, and delete shopping cart data associated with a given user name
- This repository interacts with the database to ensure that shopping cart information is reliably saved and accessible.IBasketRepository.cs - The `IBasketRepository` interface defines the methods for interacting with shopping cart data within the application
- It enables retrieval, storage, and deletion of shopping carts associated with specific user names, ensuring a robust and scalable mechanism for managing user shopping experiences.Exceptions
BasketNotFoundException.cs - Defines a custom exception, BasketNotFoundException, within the Basket API service
- This exception is thrown when a user's shopping basket cannot be found, providing a specific error message that includes the user's name
- This helps in handling and reporting errors related to missing baskets gracefully within the application.Dtos
BasketCheckoutDto.cs - BasketCheckoutDto defines the structure of data required to process a checkout request within the e-commerce system
- It encapsulates customer information, shipping and billing addresses, payment details, and the total price of the order
- This DTO facilitates communication between different services involved in the checkout process.Basket
DeleteBasket
DeleteBasketEndpoints.cs - Defines endpoints for deleting a user's shopping basket within the application
- It handles incoming DELETE requests to the "/basket/{userName}" path, processes the request using a command pattern, and returns an appropriate response indicating success or failure
- The endpoint integrates with other components like message sending and result adaptation to manage the deletion process.DeleteBasketHandler.cs - Manages the deletion of a user's shopping basket
- It receives a command containing the user's name and interacts with a repository to remove the associated basket data
- Upon successful deletion, it returns a confirmation result indicating success
- This functionality contributes to the overall e-commerce platform by allowing users to clear their shopping carts.CheckoutBasket
CheckoutBasketHandler.cs - The `CheckoutBasketHandler` orchestrates the checkout process for a user's shopping basket
- It retrieves the basket, calculates its total price, publishes a checkout event to a message queue, and then deletes the basket from storage
- This ensures that the order is processed and recorded for fulfillment.CheckoutBasketEndpoints.cs - Defines the API endpoint responsible for handling basket checkout requests within the application
- It receives a request containing basket details, processes it as a command, and returns a success or failure response to the client
- This endpoint integrates with the messaging system to send the checkout command for processing.StoreBasket
StoreBasketEndpoints.cs - Defines an API endpoint responsible for storing a user's shopping basket
- It accepts a shopping cart as input, processes the request using a command pattern, and returns a confirmation with the user's name upon successful storage
- This endpoint integrates with other components within the application to manage user baskets and their associated data.StoreBasketHandler.cs - The `StoreBasketCommandHandler` orchestrates the process of storing a shopping cart within the system
- It validates the incoming cart data, applies discounts to each item using a gRPC service, and persists the final cart to the repository
- Upon successful completion, it returns a confirmation message containing the user's name.GetBasket
GetBasketEndpoints.cs - Defines endpoints for retrieving a user's shopping basket
- It maps a GET request to a specific URL path with the user name as a parameter, processes the request using an internal query handler, and returns the retrieved shopping cart data as a JSON response
- This functionality contributes to the overall e-commerce application by enabling users to access their shopping baskets.GetBasketHandler.cs - Handles retrieving a shopping basket associated with a given user name
- It defines a query to request the basket and a handler that retrieves it from the repository, returning the shopping cart data
- This functionality is essential for managing individual user shopping experiences within the e-commerce application.Ordering
Ordering.Domain
Ordering.Domain.csproj - Defines the domain logic for order processing within the application
- It leverages the MediatR library to handle command and query operations related to orders, ensuring a clear separation of concerns between business rules and infrastructure
- Let me know if you need further clarification on any aspect of this summary or the project structure!GlobalUsing.cs - This file establishes global namespaces within the Ordering domain of the application
- It ensures that classes and types defined across various modules like abstractions, models, value objects, enums, exceptions, and events are readily accessible throughout the Ordering service's codebase.Models
OrderItem.cs - Defines the OrderItem model within the Ordering domain
- It represents a single item included in an order, encapsulating details like the order ID, product ID, quantity, and price
- This model contributes to the overall structure of managing and processing orders within the application.Customer.cs - Defines the Customer entity within the Ordering domain
- It encapsulates customer information like name and email, ensuring data integrity through validation during creation
- This model serves as a blueprint for representing individual customers in the ordering system.Product.cs - Defines the Product model within the Ordering domain
- It encapsulates product attributes like name and price, ensuring data integrity through validation during creation
- This model serves as the foundation for representing individual products in the ordering system.Order.cs - The `Order` class defines the structure and behavior of an order within the application's domain model
- It encapsulates details like customer information, shipping and billing addresses, payment method, order items, and status
- This class enables the creation, modification, and management of orders throughout their lifecycle.Enums
OrderStatus.cs - Defines the possible states an order can be in within the ordering service
- This enumeration, `OrderStatus`, provides a structured way to represent the lifecycle of an order, from its initial creation as a "Draft" to its eventual completion or cancellation.Events
OrderCreatedEvent.cs - Defines the `OrderCreatedEvent`, a record representing an order creation event within the Ordering domain
- This event adheres to the `IDomainEvent` interface, signaling a significant change in the ordering process and allowing for downstream actions or notifications based on this event.OrderUpdatedEvent.cs - Defines an event that signals a change has occurred within the ordering domain
- The `OrderUpdatedEvent` records the updated order information, allowing other components of the application to react to and process these changes within the larger system architecture.Abstractions
Entity.cs - Defines the base structure for entities within the Ordering domain
- This abstraction establishes common properties like an identifier, creation and modification timestamps, and associated user information
- It ensures consistency across all entity types used in managing order-related data.IDomainEvent.cs - Defines the blueprint for domain events within the Ordering service
- This interface ensures all domain events adhere to a consistent structure, including a unique identifier, timestamp of occurrence, and type information
- This standardization facilitates event handling and communication across various components of the application.IEntity.cs - Defines the common properties and behaviors expected of all entities within the Ordering domain
- The `IEntity` interface establishes conventions for tracking creation and modification timestamps, along with associated user identifiers
- The `IEntity` interface builds upon this foundation by requiring a unique identifier (`Id`) specific to each entity type.IAggregate.cs - Defines the core interface for aggregates within the Ordering domain
- Aggregates represent a cluster of related entities and encapsulate business logic
- This interface establishes common behaviors like managing domain events, ensuring consistency across aggregate implementations.Aggregate.cs - Defines the base structure for aggregates within the Ordering domain
- It provides a mechanism for tracking and managing domain events associated with each aggregate, enabling features like event sourcing and asynchronous processing of business logic changes
- This abstraction ensures consistency and maintainability across various ordering-related entities.ValueObjects
OrderItemId.cs - Defines a value object representing a unique identifier for an order item within the Ordering domain
- It ensures that each OrderItemId is non-empty and utilizes a GUID to guarantee uniqueness
- This class contributes to data integrity and consistency by enforcing these constraints during order item creation and management.OrderName.cs - Defines the `OrderName` value object within the Ordering domain
- It encapsulates a string representing an order name and ensures its validity through input validation
- This value object contributes to maintaining data integrity and consistency across the ordering service.Address.cs - Defines an immutable `Address` value object that encapsulates customer shipping information
- This object ensures data integrity and consistency within the ordering domain by enforcing validation rules and providing a structured representation of address details.Payment.cs - Defines the Payment value object within the Ordering domain
- It encapsulates payment card details like name, number, expiration date, CVV, and payment method
- The `Of` method constructs a valid `Payment` instance, ensuring data integrity through validation checks
- This object represents a crucial component for processing orders securely and accurately.OrderId.cs - Defines the OrderId value object within the Ordering domain
- It encapsulates a unique identifier for each order, ensuring it's not empty and adheres to the required Guid format
- This class contributes to maintaining data integrity and consistency across the ordering system.ProductId.cs - Defines a value object representing a unique product identifier within the ordering domain
- It ensures that each product ID is a non-empty GUID and provides a factory method to create valid instances, enforcing data integrity and consistency across the application.CustomerId.cs - Defines a value object representing a unique customer identifier within the ordering domain
- It encapsulates a GUID and provides methods to ensure valid customer IDs are created, preventing empty or invalid values from being used in the system.Exceptions
DomainException.cs - Defines a custom exception type, `DomainException`, within the Ordering domain layer
- This exception is specifically designed to be thrown when errors occur during business logic operations within the domain, providing a clear indication of the source of the issue.Ordering.Infrastructure
GlobalUsing.cs - GlobalUsing.cs defines a set of global namespaces used throughout the Ordering service's infrastructure layer
- It ensures consistent access to domain models, value objects, enumerations, abstractions, data access components, and Entity Framework Core functionalities, streamlining development and promoting code reusability within the project.Ordering.Infrastructure.csproj - Defines the infrastructure layer for the Ordering service
- It establishes a connection to a SQL Server database using Entity Framework Core and references the Ordering Application project, enabling data persistence and interaction within the ordering system.DependencyInjection.cs - This file configures the infrastructure layer of the Ordering service by registering dependencies within the application's service container
- It establishes connections to the database, sets up interceptors for auditing and event dispatching, and registers concrete implementations of interfaces defined in the application layer.Data
ApplicationDbContext.cs - Manages the database schema and interactions for the Ordering service
- It defines DbSet properties to represent entities like Customers, Products, Orders, and OrderItems, allowing data persistence and retrieval
- The context also utilizes Entity Framework Core conventions and configuration mappings defined within the assembly.Migrations
20241115122435_InitialCreate.Designer.cs - This code defines a database schema using Entity Framework Core
- It creates entities for Customers, Orders, OrderItems, and Products, establishing relationships between them
- Each entity has properties representing attributes like name, price, quantity, and timestamps for creation and modification.20241115122435_InitialCreate.cs - This C# code defines a database migration script using Entity Framework Core
- The script creates tables for Customers, Products, Orders, and OrderItems, establishing relationships between them
- It also defines indexes to improve query performance
- The Down method provides the reverse operations to delete these tables.ApplicationDbContextModelSnapshot.cs - This code defines a database schema using Entity Framework Core
- It establishes relationships between entities like Customers, Orders, OrderItems, and Products
- The schema includes properties for each entity and specifies primary keys, foreign keys, and data types
- This structure is essential for managing and querying relational data within an application.Interceptors
AuditableEntityInterceptor.cs - AuditableEntityInterceptor manages the creation and modification timestamps for entities within the Ordering service's database
- It automatically sets the "CreatedBy", "CreatedAt", "LastModifiedBy", and "LastModified" properties on each entity based on its state (Added, Modified) ensuring a consistent audit trail of data changes.DispatchDomainEventsInterceptor.cs - This interceptor manages the publication of domain events within the Ordering service's database context
- It intercepts database saving operations and dispatches any accumulated domain events to the MediatR bus for further processing
- This ensures that domain events are published consistently after changes are made to the database.Extensions
DatabaseExtensions.cs - DatabaseExtensions initializes and populates the application database
- It ensures that essential data such as customers, products, and orders are present when the application starts
- This initialization process includes migrating the database schema and seeding it with initial data sets defined in the InitialData class.InitialData.cs - InitialData provides sample data for the Ordering system, initializing customers, products, and orders with items
- This ensures a populated database for testing and development purposes within the larger application architecture.Configurations
OrderItemConfiguration.cs - Defines the structure and relationships of OrderItem entities within the database schema
- It establishes a primary key for each order item, maps the product association, and enforces required fields for quantity and price
- This configuration ensures data integrity and consistency for order items in the Ordering service.ProductConfiguration.cs - ProductConfiguration defines the structure and behavior of the Product entity within the Ordering service's database schema
- It establishes the primary key, ensures a specific data type conversion for the product ID, and sets constraints on the product name field
- This configuration directly impacts how product data is stored and retrieved, ensuring data integrity and consistency within the ordering system.CustomerConfiguration.cs - Defines the structure and properties of the 'Customer' entity within the Ordering service's database schema
- It specifies a unique identifier for each customer, enforces data validation rules for name and email, and ensures that email addresses are unique across all customers
- This configuration contributes to the overall data integrity and consistency of the ordering system.OrderConfiguration.cs - OrderConfiguration defines the structure and relationships of Order entities within the database schema
- It specifies data types, constraints, and foreign keys to ensure accurate representation and efficient retrieval of order information, including customer details, order items, shipping and billing addresses, payment methods, status, and total price.Ordering.Application
Ordering.Application.csproj - Defines the Ordering.Application project, a core component responsible for orchestrating business logic within the ordering domain
- It leverages the BuildingBlocks library for messaging and foundational services, interacts with the Ordering Domain for data access, and utilizes Entity Framework Core for database interactions.GlobalUsing.cs - GlobalUsing.cs establishes a shared namespace within the Ordering Application project
- It ensures that various components like domain models, value objects, CQRS implementations, data access layers, DTOs, exceptions, and event handling mechanisms are readily accessible across different parts of the application codebase.DependencyInjection.cs - The `DependencyInjection` class within the Ordering Application module configures and registers essential services required by the ordering application
- It sets up dependency injection for MediatR, enabling command and query handling, integrates feature management capabilities, and connects the application to the message broker for asynchronous communication.Data
IApplicationDbContext.cs - Defines the interface for interacting with the application's database context
- It specifies the available DbSet properties for Orders, Customers, Products, and OrderItems, enabling data access and manipulation within the Ordering application
- The interface also includes a SaveChangesAsync method for persisting changes to the database.Extentions
OrderExtensions.cs - The `OrderExtensions` class facilitates the transformation of Order objects into their corresponding DTO (Data Transfer Object) representations
- This conversion is crucial for transferring order data between different layers of the application, enabling seamless communication and data exchange within the ordering service's architecture.Exceptions
OrderNotFoundException.cs - Defines a custom exception, OrderNotFoundException, within the Ordering application's exception handling layer
- This exception is specifically raised when an order with a given ID cannot be found in the system, providing a clear indication of this failure scenario to calling code and facilitating appropriate error handling.Dtos
OrderItemDto.cs - Defines the `OrderItemDto` data transfer object within the Ordering application
- This structure represents a single item within an order, encapsulating its OrderId, ProductId, Quantity, and Price
- It facilitates communication between different layers of the application, ensuring consistent data representation when handling order items.AddressDto.cs - Defines the structure for representing an address within the ordering application
- This data transfer object (DTO) encapsulates essential address information like name, email, and location details, facilitating communication between different layers of the application.OrderDto.cs - The `OrderDto` class defines a data transfer object representing an order within the application layer
- It encapsulates essential order information such as customer details, shipping and billing addresses, payment information, status, and a list of associated order items
- This structure facilitates seamless communication between different components of the ordering service.PaymentDto.cs - Defines the PaymentDto, a data transfer object used within the Ordering application to represent payment information
- This DTO encapsulates details like card name, number, expiration date, CVV, and payment method, facilitating secure and structured communication between different components of the ordering system.Orders
Commands
DeleteOrder
DeleteOrderCommandHandler.cs - Handles the deletion of an order within the application
- It retrieves the order from the database based on the provided order ID and removes it if found
- The command handler then saves the changes to the database and returns a confirmation result indicating successful deletion.DeleteOrderCommand.cs - Defines the structure and validation rules for deleting an order within the ordering service
- The `DeleteOrderCommand` encapsulates the order ID required for deletion, while the `DeleteOrderResult` indicates the success or failure of the operation
- This command follows a pattern common in CQRS architectures, separating commands from queries for a more structured application design.UpdateOrder
UpdateOrderCommandHandler.cs - This command handler processes requests to update existing orders within the system
- It retrieves the order from the database, updates its details based on provided data, and saves the changes
- The handler ensures that the order exists before proceeding with the update and handles potential exceptions if the order is not found.UpdateOrderCommand.cs - Defines the `UpdateOrderCommand` used to modify existing orders within the Ordering service
- It encapsulates order details as a DTO and leverages FluentValidation to ensure data integrity before processing the update request
- The command's successful execution is indicated by an `UpdateOrderResult`.CreateOrder
CreateOrderCommandHandler.cs - This command handler processes incoming create order requests
- It constructs a new order object based on the provided order details, including customer information, shipping and billing addresses, payment method, and order items
- The newly created order is then persisted to the database.CreateOrderCommand.cs - Defines the structure and validation rules for creating new orders within the application
- It specifies the required data fields for an order, including its name, customer ID, and list of items
- This command ensures data integrity and consistency when processing new order requests.Queries
GetOrders
GetOrdersQueryHandler.cs - Retrieves orders from the database based on pagination parameters provided by a GetOrdersQuery
- The handler fetches a specified number of orders, ordered alphabetically by order name, and calculates the total count of orders available
- It then constructs a PaginatedResult containing the retrieved orders and relevant metadata for display or further processing within the application.GetOrdersQuery.cs - Defines the `GetOrdersQuery` used to retrieve orders within the Ordering application
- This query accepts a pagination request and returns a result containing paginated orders represented as `OrderDto` objects
- This functionality supports retrieving orders in a controlled manner, allowing for efficient data retrieval based on user needs.GetOrdersByName
GetOrdersByNameQueryHandler.cs - The `GetOrdersByNameQueryHandler` retrieves orders from the database based on a provided name
- It queries the `Orders` table, including related order items, and filters results to match the specified name
- The handler then returns a list of orders in a formatted DTO (Data Transfer Object) suitable for presentation or further processing within the application.GetOrdersByNameQuery.cs - Defines a query to retrieve orders based on a given name within the Ordering application
- It encapsulates the criteria for the search (a customer's name) and specifies the expected result structure, which includes a collection of order details
- This query contributes to the overall functionality of retrieving and managing order information within the system.GetOrdersByCustomer
GetOrdersByCustomerQueryHandler.cs - This handler retrieves orders associated with a specific customer from the database
- It fetches order details, including order items, and sorts them alphabetically by order name
- The retrieved data is then transformed into a format suitable for presentation to the user within the application's ordering service.GetOrdersByCustomerQuery.cs - Defines a query to retrieve orders associated with a specific customer within the ordering service
- It encapsulates the request parameters and the expected result structure, facilitating communication between application layers and data access components
- This aligns with the project's goal of providing a modular and well-defined architecture for managing order information.EventHandlers
Domain
OrderCreatedEventHandler.cs - This event handler processes the "OrderCreatedEvent" within the Ordering service's application layer
- It logs the event and, if the "OrderFullfilment" feature is enabled, publishes an integration event representing the created order to a message bus
- This enables downstream services to be notified about new orders.OrderUpdatedEventHandler.cs - Handles the OrderUpdatedEvent within the Ordering application's domain layer
- When an OrderUpdatedEvent is raised, this event handler logs a message indicating the event type was handled
- This ensures proper logging and tracking of domain events within the ordering system's architecture.Integration
BasketCheckoutEventHandler.cs - This event handler processes the "BasketCheckoutEvent", signifying a customer's checkout action
- It maps the event data into a "CreateOrderCommand" which is then sent to initiate the order creation process within the Ordering service
- This integration ensures a seamless transition from the shopping cart to the order management system.Ordering.API
GlobalUsing.cs - GlobalUsing.cs establishes a foundational framework within the Ordering API by globally importing essential libraries and namespaces
- This file ensures seamless integration of Carter for web API development, Mapster for object mapping, MediatR for handling asynchronous requests, and custom DTOs defined in the Ordering.Application project.Ordering.API.http - Defines the base address for the Ordering API within the application's architecture
- This configuration ensures proper communication between different services and components, facilitating seamless order processing across the system.DependencyInjection.cs - Configures the Ordering API's dependencies and services
- It sets up Carter as the web framework, integrates Swagger for documentation, implements health checks using SQL Server, and configures exception handling
- The file also enables development features like Swagger UI and HTTPS redirection.Dockerfile - This Dockerfile defines the build and deployment process for the Ordering API service within the larger application architecture
- It leverages multi-stage builds to efficiently compile, publish, and containerize the application, ensuring a streamlined and optimized deployment process.Ordering.API.csproj - Defines the Ordering API project, a web application built using ASP.NET Core that exposes endpoints for managing orders
- It leverages dependency injection to integrate with the Ordering Application and Infrastructure projects, providing a robust and scalable solution for order processing
- The API utilizes Swagger documentation and health checks for monitoring and developer convenience.appsettings.Development.json - Configures the development environment for the Ordering API service
- It defines connection strings for the database and message broker, sets feature flags for order fulfillment, and specifies logging levels for different components within the application.appsettings.json - Configures the application's environment settings
- It defines connection strings for accessing the database and message broker, sets logging levels, and specifies allowed hosts for secure communication
- These configurations are essential for the Ordering API to function correctly within the overall project architecture.Program.cs - The `Program.cs` file bootstraps the Ordering API application
- It configures services such as application logic, infrastructure components, and API endpoints
- Furthermore, it initializes the database during development and sets up the request pipeline to handle incoming HTTP requests.Properties
launchSettings.json - Configures the development environment for the Ordering API within the project
- It defines launch settings for different profiles like HTTP, HTTPS, and IIS Express, specifying URLs, ports, authentication methods, and environment variables
- These settings enable seamless local development and debugging of the Ordering API.Endpoints
DeleteOrder.cs - The `DeleteOrder` class defines an endpoint within the Ordering API responsible for deleting an order by its unique identifier
- It sends a `DeleteOrderCommand` to the application layer, processes the result, and returns an appropriate HTTP response indicating success or failure.UpdateOrder.cs - Defines an API endpoint for updating existing orders within the Ordering system
- It accepts a request containing updated order details, processes the update using an internal command handler, and returns a success/failure response to the client
- This endpoint integrates with the broader application architecture by utilizing message sending mechanisms for asynchronous processing of updates.GetOrders.cs - Defines an endpoint within the Ordering API responsible for retrieving orders
- It accepts pagination parameters and utilizes a query handler to fetch orders from the application layer
- The retrieved orders are then presented as a paginated response, adhering to standard HTTP status codes and documentation conventions.GetOrdersByCustomer.cs - Defines an API endpoint for retrieving customer orders
- It accepts a customer ID as input and utilizes the `GetOrdersByCustomerQuery` to fetch relevant order data from the application layer
- The retrieved orders are then formatted into a response object and returned to the client with a successful status code.GetOrdersByName.cs - Defines an API endpoint for retrieving orders based on a provided name
- This endpoint leverages the `GetOrdersByNameQuery` from the application layer to fetch relevant order data and returns the results as a `GetOrdersByNameResponse` object
- The endpoint is documented with clear summaries and descriptions, adhering to best practices for API design within the Ordering service.CreateOrder.cs - Defines an endpoint within the Ordering API responsible for creating new orders
- It accepts a CreateOrderRequest containing order details, processes the request using a command handler, and returns a Created response with the newly generated order ID
- This endpoint integrates seamlessly with the application's ordering service to manage order creation.Discount
Discount.Grpc
discountdb - Please provide me with the code file and the "PROJECT STRUCTURE" context details so I can generate a succinct summary for you
- Once you give me that information, I'll be able to:
- Analyze the code: Understand its functionality within the larger project.
- Relate it to the architecture: Explain how this file contributes to the overall design and goals of the project.
- Write a clear summary: Provide a concise explanation of what the code achieves, avoiding technical jargon and focusing on the "big picture."
Let's work together to make your open-source project even better!
Dockerfile - This Dockerfile defines the build and deployment process for a gRPC service responsible for handling discount calculations within the application
- It leverages multi-stage builds to optimize image size, ensuring a lean and efficient runtime environment for the service.Discount.Grpc.csproj - Defines the gRPC service for managing discounts within the application's architecture
- It leverages gRPC for communication, Mapster for object mapping, and Entity Framework Core for data persistence using a SQLite database
- The service exposes functionalities related to discount creation, retrieval, and modification through well-defined API endpoints.appsettings.Development.json - Configures the Discount gRPC service's environment settings during development
- It specifies the connection string to access the discount database and sets the logging level for information messages
- These configurations are essential for the service to function correctly within the larger project architecture, enabling it to interact with the database and log relevant events.appsettings.json - Configures the Discount gRPC service by defining connection strings to the database, logging levels, allowed hosts, and Kestrel endpoint protocols
- These settings are crucial for the service to function correctly within the larger application architecture, enabling communication with the database, managing logs, and establishing secure network connections.Program.cs - This program bootstraps a gRPC service responsible for managing discount information within the application
- It configures a database connection using SQLite and registers the DiscountService to handle incoming gRPC requests related to discounts
- The program also sets up database migrations to ensure data schema consistency.Protos
discount.proto - Defines the gRPC service interface for managing discount coupons within the application
- It specifies methods for retrieving, creating, updating, and deleting discounts based on product names
- The service utilizes aCouponModel
data structure to represent discount information..config
dotnet-tools.json - The dotnet-tools.json
file configures tools used within the Discount service's gRPC implementation
- It specifies the version of Entity Framework Core and its associated commands, enabling database operations essential for managing discount data within the broader application architecture.Models
Coupon.cs - Defines the structure of a coupon within the Discount service's gRPC API
- This model represents a single discount offer, including its unique identifier, product name, description, and monetary value
- It enables seamless communication between clients and the Discount service for retrieving and applying coupons during checkout processes.Migrations
DiscountContextModelSnapshot.cs - Defines the structure of the DiscountContext
database within the application
- It specifies the schema for theCoupons
table, outlining columns likeId
,Amount
,Description
, andProductName
- This file also includes initial sample data for two coupons: one for an "IPhone X" and another for a "Samsung 10".20241111105053_InitialCreate.cs - This migration script establishes the initial database structure for the Discount service
- It creates a "Coupons" table to store information about available discounts, including product name, description, and discount amount
- The script also populates this table with two initial coupon entries.20241111105053_InitialCreate.Designer.cs - This file defines the initial database schema for the Discount Service within the larger application architecture
- It specifies the structure of the "Coupons" table, including columns for ID, Amount, Description, and ProductName, along with initial sample data.Properties
launchSettings.json - Defines the launch settings for the Discount gRPC service within the larger project architecture
- It specifies how the service runs, including the port number and environment variables used during development
- This configuration allows developers to easily start and debug the gRPC service as part of the overall application.Services
DiscountService.cs - DiscountService handles all interactions related to coupons within the application
- It retrieves existing coupons based on product name, creates new coupons, updates existing ones, and deletes coupons as requested by clients
- This service acts as a central point of access for managing coupon data within the system.Data
DiscountContext.cs - DiscountContext establishes the data access layer for managing coupon information within the Discount gRPC service
- It defines a database context using Entity Framework Core, enabling interactions with a DbSet of Coupon entities to store, retrieve, and manipulate discount data.Extentions.cs - The Extentions
class within the Discount gRPC service's data layer provides a mechanism to apply database migrations during application startup
- It leverages dependency injection to access theDiscountContext
and ensures that the database schema is updated to reflect any changes defined in the migration scripts.Catalog
Catalog.API
GlobalUsing.cs - GlobalUsing.cs establishes a shared namespace within the Catalog API project
- It imports essential libraries and frameworks used throughout the application, including Carter for web requests, Mapster for object mapping, MediatR for handling asynchronous requests, Marten for document database interactions, and FluentValidation for data validation.Dockerfile - This Dockerfile defines the build process for a .NET API application named Catalog.API
- It utilizes multiple stages to efficiently build, publish, and containerize the application
- The final stage creates a runnable image that exposes ports 8080 and 8081, allowing the API to be accessible within a Docker environment.global.json - Defines the SDK version and roll forward strategy used within the Catalog API service
- This configuration ensures compatibility with the latest features of the .NET SDK, enabling the development team to leverage the most up-to-date tools and functionalities
- Let me know if you have any other questions about this project or need further assistance!Catalog.API.csproj - Defines the Catalog API project within a larger microservices architecture
- It leverages ASP.NET Core and integrates with external services like Marten for data persistence and Swashbuckle for API documentation
- The project also incorporates health checks and utilizes the BuildingBlocks library for shared functionality across the application.appsettings.Development.json - Configures the development environment settings for the Catalog API service
- It defines the connection string to access the CatalogDb database and sets the logging level for different categories within the application
- These configurations are crucial for the API to function correctly during development.appsettings.json - The appsettings.json file configures the application's runtime environment within the Catalog API service
- It defines connection details for the database, sets logging levels for different areas of the application, and specifies allowed hostnames for accessing the API.Program.cs - Configures the Catalog API application by defining services, middleware, and endpoints
- It sets up dependency injection, integrates with Swagger for documentation, enables CORS for cross-origin requests, and registers health checks for monitoring application status
- The file also initializes Marten database interactions and configures exception handling.Models
Product.cs - Defines the structure of a product within the e-commerce catalog
- This model specifies attributes such as the product's ID, name, category, description, image file path, and price
- It serves as the blueprint for representing individual products in the API and database.Properties
launchSettings.json - Defines the configuration settings for launching and debugging the Catalog API within various environments
- It specifies URLs, ports, authentication methods, and environment variables used during development, testing, and deployment to IIS Express or Docker containers.Data
CatalogInitialData.cs - CatalogInitialData populates the product catalog with sample data when the application starts
- It utilizes a Faker library to generate realistic product information, including names, prices, descriptions, and categories
- This ensures a populated database for initial testing and development purposes within the larger e-commerce application.Exceptions
ProductNotFoundException.cs - Defines a custom exception type, ProductNotFoundException, within the Catalog API service
- This exception is specifically raised when a requested product cannot be found based on its provided identifier (Guid)
- It extends the built-in NotFoundException, providing a more specific error message indicating the missing resource.Products
DeleteProduct
DeleteProductEndPoint.cs - Defines an endpoint within the API responsible for deleting a product by its ID
- This endpoint receives a product ID as input and sends a command to the application's core logic to delete the corresponding product record
- The endpoint returns a success or failure indication to the caller.DeleteProductHandler.cs - Manages the deletion of a product from the catalog service
- It receives a product ID as input and orchestrates the retrieval, removal, and saving of changes to the database
- If the product is not found, it throws an appropriate exception.UpdateProduct
UpdateProductEndPoint.cs - The UpdateProductEndPoint
class defines an API endpoint responsible for updating product information within the system
- It accepts a request containing updated product details and sends a command to the application's core logic for processing
- The endpoint returns a success or failure response indicating the outcome of the update operation.UpdateProductHandler.cs - This file defines the logic for updating a product within the application's catalog service
- It handles incoming update requests, validates the provided data, retrieves the existing product from storage, modifies its attributes based on the request, and saves the changes
- Successful updates return an indication of success.GetProductById
GetProductByIdHandler.cs - This file defines the logic for retrieving a specific product from the catalog based on its unique identifier
- It utilizes a query handler to interact with the database, ensuring that a valid product ID is provided and handling the scenario where a product is not found
- The retrieved product information is then returned as a result object.GetProductByIdEndPoint.cs - Defines an endpoint within the API that retrieves a product by its unique identifier
- This endpoint accepts a product ID as input and returns a corresponding product object upon successful retrieval
- It leverages message sending to interact with other parts of the application, ensuring a robust and scalable architecture.CreateProduct
CreateProductHandler.cs - This file defines the logic for creating new products within the application
- It handles incoming product creation requests, validates their data against predefined rules, and persists the validated product information to the database
- Upon successful creation, it returns a unique identifier for the newly created product.CreateProductEndPoint.cs - Defines an endpoint within the Catalog API responsible for creating new products
- It accepts a product creation request, processes it as a command, and returns a successful response with the newly created product's ID upon completion
- This endpoint integrates with other parts of the system to handle database interactions and generate appropriate responses based on success or failure.GetProducts
GetProductsHandler.cs - Handles retrieving paginated product data from the database
- It processes a query specifying page number and size, then fetches products using Marten's pagination capabilities
- The retrieved products are returned as a result object, enabling seamless integration with the application's presentation layer.GetProductsEndPoint.cs - Defines an endpoint within the Catalog API responsible for retrieving product information
- It accepts a request containing pagination parameters and returns a list of products as a response
- This endpoint leverages dependency injection to interact with the application's query handling logic, ensuring efficient data retrieval and presentation.GetProductByCategory
GetProductByCategoryHandler.cs - This file defines a handler responsible for retrieving products based on a given category within the application's catalog service
- It processes queries to fetch products whose categories match the specified search term and returns a result containing the matching products
- This functionality contributes to the overall goal of providing users with a searchable and browsable catalog of products.GetProductByCategoryEndPoint.cs - Defines an API endpoint that retrieves a list of products based on a given category
- It utilizes theISender
interface to send a query to retrieve products and returns a response containing the retrieved products as a collection
- This endpoint contributes to the overall functionality of the e-commerce platform by enabling users to filter products by category.
Before getting started with VerticalSliceCommerceMicroservice, ensure your runtime environment meets the following requirements:
- Programming Language: CSharp
- Package Manager: Nuget
- Container Runtime: Docker
Install VerticalSliceCommerceMicroservice using one of the following methods:
Build from source:
- Clone the VerticalSliceCommerceMicroservice repository:
❯ git clone https://github.com/hakanereenn/VerticalSliceCommerceMicroservice
- Navigate to the project directory:
❯ cd VerticalSliceCommerceMicroservice
- Install the project dependencies:
❯ dotnet restore
❯ docker build -t hakanereenn/VerticalSliceCommerceMicroservice .
Run VerticalSliceCommerceMicroservice using the following command:
Using nuget
❯ dotnet run
❯ docker run -it {image_name}
Run the test suite using the following command:
Using nuget
❯ dotnet test
- Inspired by Mehmet Özkaya