-
Notifications
You must be signed in to change notification settings - Fork 44
Entities & State
Charles Solar edited this page Jun 13, 2018
·
2 revisions
The DDD library we use Aggregates.NET (also my own) defined aggregates and entities as simply "Entities." It makes no effort to separate the two. By the structure of the project here you'll see I've defined my bounded contexts as 1 of each "Context" folder.
Looking at the Basket entity we'll find various methods representing actions available to baskets.
public class Basket : Aggregates.Entity<Basket, State>
{
private Basket() { }
public void Initiate(Identity.User.State user)
{
Apply<Events.Initiated>(x =>
{
x.BasketId = Id;
x.UserName = user?.Id;
});
}
public void Claim(Identity.User.State user)
{
Rule("Claimed", x => !string.IsNullOrEmpty(State.UserName), "Basket already claimed");
Apply<Events.BasketClaimed>(x =>
{
x.BasketId = Id;
x.UserName = user.Id;
});
}
public void Destroy()
{
Apply<Events.Destroyed>(x =>
{
x.BasketId = Id;
});
}
}
Basket's can be initiated - with an optional user attached to it. They can be claimed (if not already claimed by a user) - which means the user logged into the site while checking out. And finally they can be destroyed. Each of these actions raises an event which is saved to the stream and applied to the basket's state object.
public class State : Aggregates.State<State>
{
public string UserName { get; private set; }
private void Handle(Events.Initiated e)
{
this.UserName = e.UserName;
}
private void Handle(Events.BasketClaimed e)
{
this.UserName = e.UserName;
}
}