IConfiguration vs IOptions NET
Synchronous and Asynchronous in .NET Core
Model Binding and Validation in ASP.NET Core
ControllerBase vs Controller in ASP.NET Core
ConfigureServices and Configure methods
IHostedService interface in .NET Core
ASP.NET Core request processing
| Queue Models | CQRS | |
📜 Event Sourcing |
Event Sourcing is a design pattern where the state of an application is derived from a sequence of events rather than storing only the current state. Every change is captured as an immutable event and stored in an event store. The current state can be rebuilt by replaying these events.
Here’s a simplified example of Event Sourcing for an Order Aggregate:
// Event definition
public abstract class Event
{
public Guid Id { get; set; } = Guid.NewGuid();
public DateTime OccurredOn { get; set; } = DateTime.UtcNow;
}
public class OrderCreated : Event
{
public string OrderId { get; set; }
public string Customer { get; set; }
}
public class ItemAdded : Event
{
public string OrderId { get; set; }
public string Item { get; set; }
}
// Aggregate Root
public class Order
{
public string OrderId { get; private set; }
public string Customer { get; private set; }
public List<string> Items { get; private set; } = new();
public List<Event> Changes { get; private set; } = new();
public static Order Create(string orderId, string customer)
{
var order = new Order();
var @event = new OrderCreated { OrderId = orderId, Customer = customer };
order.Apply(@event);
order.Changes.Add(@event);
return order;
}
public void AddItem(string item)
{
var @event = new ItemAdded { OrderId = this.OrderId, Item = item };
Apply(@event);
Changes.Add(@event);
}
private void Apply(OrderCreated e)
{
OrderId = e.OrderId;
Customer = e.Customer;
}
private void Apply(ItemAdded e)
{
Items.Add(e.Item);
}
}
Event Sourcing is a powerful pattern for building auditable, event-driven systems. In .NET Core, it can be implemented with custom code or libraries like EventStoreDB or Marten. While it adds complexity, it provides unmatched traceability, flexibility, and integration with CQRS.
| Queue Models | CQRS | |