What is CQRS?
-
Commands: These are actions that change data, like adding a new order.
-
Queries: These are actions that only read data, like getting a list of orders.
Key Concepts of CQRS:
-
Commands: Used to update or change something (e.g., CreateOrderCommand).
-
Queries: Used to get information (e.g., GetOrdersQuery).
- Separation of Concerns: The read and write parts are separate, allowing them to be managed more effectively.
- Scalability: Read and write systems can grow on their own when needed.
Benefits of CQRS:
-
Better Performance: Read and write operations are optimized on their own.
-
Improved Security: Different permissions can be set for commands and queries.
- More Flexibility: We can change the way we show data without affecting how we save it.
- Works Well with Event Sourcing: Makes tracking changes easier.
What is Event Sourcing?
Key Concepts of Event Sourcing:
-
Event Store: A place where all events are saved (e.g., OrderCreated, OrderShipped).
-
Event Replay: We can rebuild the entire state of the app using past events.
- Event Handlers: These react to events and perform actions.
- Projections: Create simple views from the list of events for easy reading.
Benefits of Event Sourcing:
-
Easy Debugging: You can see exactly what happened and when.
-
Scalability: Events can be handled in different systems at the same time.
- Consistent Data: Everything is recorded and consistent.
- Flexible Read Models: Different views of data can be built easily.
How to Use CQRS and Event Sourcing in .NET Core
Step 1: Install Required Packages
You need to add some libraries to your project. Use the terminal or command line:
dotnet add package MediatR
dotnet add package MediatR.Extensions.Microsoft.DependencyInjection
dotnet add package Newtonsoft.Json
Step 2: Create the Order Model
public class Order
{
public Guid Id { get; set; }
public string CustomerName { get; set; }
public List<string> Items { get; set; }
public string Status { get; set; }
}
Step 3: Create Command and Handler
Command to Create an Order:
using MediatR;
public class CreateOrderCommand : IRequest<Guid>
{
public string CustomerName { get; set; }
public List<string> Items { get; set; }
}
Handler to Process the Command:
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Newtonsoft.Json;
using System.IO;
public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, Guid>
{
public async Task<Guid> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
{
var orderId = Guid.NewGuid();
var order = new Order {
Id = orderId,
CustomerName = request.CustomerName,
Items = request.Items,
Status = "Created"
};
var eventData = JsonConvert.SerializeObject(order);
await File.AppendAllTextAsync("eventstore.txt", eventData + "\n");
return orderId;
}
}
Step 4: Create Query and Handler
Query to Get Orders:
using MediatR;
public class GetOrdersQuery : IRequest<List<Order>> {}
Handler to Process the Query:
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Newtonsoft.Json;
using System.IO;
public class GetOrdersHandler : IRequestHandler<GetOrdersQuery, List<Order>>
{
public async Task<List<Order>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
{
var orders = new List<Order>();
var lines = await File.ReadAllLinesAsync("eventstore.txt");
foreach (var line in lines)
{
var order = JsonConvert.DeserializeObject<Order>(line);
orders.Add(order);
}
return orders;
}
}
Step 5: Setup MediatR in Your Project
In your Program.cs, register MediatR like this
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(Program).Assembly));
var app = builder.Build();
app.Run();
Step 6: Test the App
Create an Order (POST Request)
POST /createOrder
{
"customerName": "John Doe",
"items": ["Laptop", "Mouse"]
}
Get All Orders (GET Request)
GET /getOrders
Sample Response:
[
{
"id": "12345-67890",
"customerName": "John Doe",
"items": ["Laptop", "Mouse"],
"status": "Created"
}
]
Conclusion
Let’s work together to build smart, fast, and scalable software. Contact us today for a free consultation!
Brijesh Hirapara
A highly skilled .NET Full Stack Developer proficient in MVC, .NET Core, C#, SQL, jQuery. Committed to delivering efficient, high-quality solutions by simplifying complex projects with technical expertise and innovative thinking.
Reply