Recently began implementing domain events in my domain layer which really allows me to decouple the application from the domain. Eventually, I would like to get a full-scale CQRS w/Event Sourcing infrastructure.
The question I have is that I have an Account
class and one of the use cases is to be able to rename it. However, there is a domain constraint that says "no two accounts can have the same name". Based on my quick design I am assuming that this should be implemented with a domain service that checks if the account name is already taken, and if not then rename the account. I thought maybe I could get away from a domain service by using domain events, but all my domain event handlers reside in the application layer (not the domain layer). I obviously don't want to have any business logic in the application layer.
Am I understanding the difference between domain services and domain events correctly? It seems to me (based on what I've read) is that domain events allow you to decouple the application layer from the domain layer, but when it comes to ensuring consistency between multiple aggregates, I need to use domain services. Or is this possible to do it with domain events and keep everything isolated to the domain layer? My Account
class looks like:
public class Account
{
public string Name { get; private set; }
public Account(string name) { // blah // }
public void AddSubAccount(Account subAccount)
{
// do work
}
public void RemoveSubAccount(Account subAccount)
{
// do work
}
public void Rename(string newName)
{
Name = newName;
// How to ensure domain model invariants remain true?
// No two accounts can have same name
// Domain Event example:
// DomainEvents.Publish(new AccountRenamedEvent(oldName, newName));
}
}