I think that checking for uniqueness is the responsibility of the repository. The repository knows about all aggregates, because it intends to simulate a collection of domains, so it is natural to set a repository of uniqueness (for example, what you expect from HashMap, for example).
// repository interface Users { // implementation executes SQL COUNT in case of relation DB bool IsNameUnique(String name); // implementation will call IsNameUnique and throw if it fails void Add(User user); }
This is an opaque abstraction in a sense, because in a multi-user environment, it must be applied on the side of the data warehouse (for example, a UNIQUE SQL constraint or a lock).
IsNameUnique should probably not be called from a user aggregate; I would move this call to the application or domain service, depending on how the rest of your application is structured.
See Uniqueness Verification in the CQRS architecture for an alternative approach.
source share