How do I handle "singletons" in domain driven design?

I have (for instance) a domain object Account with a property EmailAddress which should be unique. To validate this I need to put all EmailAddress's in a large aggregate so that they can be validated in the same tx-scope? But how do I make sure there's only one such aggregate to validate EmailAddress's in this domain? Do the application need to be prepared with ids of singletons like this? Should domains have a definitive "Root"-aggregate to reference other aggregates such as singletons? Should the app have a synchronous index to reference/validate singletons in the domain? Or should it be a asynch (stateful?) index to just reference singletons without validating it? Other ways?

(I'm not using any particular database system)

  • Does this answer your question? How to handle business rules that are "uniqueness" constraints?
    – Rik D
    Jun 15 at 11:59
  • The domain model just needs to express the business rules at a high level, it doesn't need to perform all the actual logic needed to make them happen - think about it, you're already calling libraries and services external to your domain all over the place in order to make your business logic actually do something. Nothing in DDD says that you have to pull all the emails into your domain code and check for uniqueness there (although you can do that if you want). Instead, you could have... 1/2 Jun 15 at 13:57
  • ...a domain service that provides an interface to check for email uniqueness, and logic built around that result (thus expressing the constraint in the domain model), and then implement it in the infrastructure layer by calling your data store, asking it to check for you. This is not splitting the business logic between the domain and the database, because the database isn't hiding additional business logic behind that call, that isn't otherwise expressed in the domain. 2/2 Jun 15 at 13:57
  • Thanks for your comments, but I wasn't really asking about how to specifically handle uniqueness in DDD. My solution for that is to have a larger aggregate with all unique values in the same tx-scope (not necessarily in memory). But the question then becomes how to ensure that the domain only contains one such aggregate, or how to know what such aggregate should validate uniqueness, supposing the domain technically can contain any number of aggregates of the same type. Jun 15 at 18:21
  • 1
    The easiest way is to use a DI container that is capable of rendering objects having Singleton scope. Jun 16 at 0:27


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.