Aggregates manage state and enforce business rules. To implement one:
- Inherit from
AggregateRoot. - Use
ApplyChange(event) to record new state changes. - Implement
Apply(event) private methods to update the internal state when an event is applied (this is used during rehydration). - Provide a private parameterless constructor for rehydration purposes.
public class Product : AggregateRoot
{
private string _name;
private decimal _price;
private bool _discontinued;
public Product(Guid id, string name, decimal price)
{
Id = id;
ApplyChange(new ProductCreated(id, name, price));
}
private Product() { } // For rehydration
public void ChangePrice(decimal newPrice)
{
if (_discontinued)
throw new InvalidOperationException("Cannot change price of discontinued product");
ApplyChange(new ProductPriceChanged(Id, newPrice));
}
private void Apply(ProductCreated e)
{
_name = e.Name;
_price = e.Price;
}
private void Apply(ProductPriceChanged e)
{
_price = e.NewPrice;
}
}