Contact Us : +91 90331 80795

Blog Details

Breadcrub
Blog Detail

How to build Powerful Applications Using CQRS and Event Sourcing in .NET Core

In today’s world, software needs to handle a lot of users and data. It also needs to be fast and easy to update. Two useful ways to make this happen are CQRS and Event Sourcing. These are specialized design patterns that help developers build more effective apps. In this guide, we will explain what they are, how they help, and how you can use them with .NET Core.
 
 

What is CQRS?

 
CQRS stands for Command Query Responsibility Segregation. It means we split the way we handle data into two parts:
 
  • 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.

This separation helps us build apps that are easier to understand and grow.
 

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?

 
Event Sourcing is a design pattern that saves every change to the system as an event. Instead of just updating the current data, we record what happened and use those records to build the final result.
 

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

 
Let’s see how you can create a small project using these ideas 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

To test if everything works:
 
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

 
More than 65% of modern apps are now using microservices and event-based designs to handle big workloads and large user bases. CQRS and Event Sourcing in .NET Core gives you a smart way to build apps that are strong, flexible, and ready for growth.
 
At Sparkle Web, we build software using CQRS and Event Sourcing with .NET Core. We help startups and big companies make systems that handle real-time data, grow easily, and work without errors.
 
Whether you need an online store, a SaaS app, or a custom tool, we can help you build it the right way.
 
Need expert help?

Let’s work together to build smart, fast, and scalable software. Contact us today for a free consultation!

    Author

    • Owner

      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.

    Contact Us

    Free Consultation - Discover IT Solutions For Your Business

    Unlock the full potential of your business with our free consultation. Our expert team will assess your IT needs, recommend tailored solutions, and chart a path to success. Book your consultation now and take the first step towards empowering your business with cutting-edge technology.

    • Confirmation of appointment details
    • Research and preparation by the IT services company
    • Needs assessment for tailored solutions
    • Presentation of proposed solutions
    • Project execution and ongoing support
    • Follow-up to evaluate effectiveness and satisfaction

    • Email: info@sparkleweb.in
    • Phone Number:+91 90331 80795
    • Address: 303 Capital Square, Near Parvat Patiya, Godadara Naher Rd, Surat, Gujarat 395010