Generating identities for entities in DDD

早过忘川 提交于 2019-11-29 19:06:17

问题


Edit

To further clarify my initial problem, I rewrote the question with more 'DDD'-termini, common patterns and discussion arguments. The orginal version can be found under revisions.


Where and how are identities for entities/aggregate roots being generated inside the domain when correctly applying DDD?

I need to assign unique identities to my entities, either upon creation or persisting. Those identities can come in several styles

  • Computed (based on the characteristics of an entity, hence based on business requirements)
  • Natural (based on a certain set of rules, hence based on business logic)
  • Surrogates (based on randomly generated values with no business meaning)

There are many approaches for the task of generation and assignment of identities, from using factories to create identities, delegation to the infrastructure using ORM or database generation etc. However, if correctly applying DDD, where and how should identities be generated, considering that we don't want anemic domain models and injection of services into entities?

Requirements as declared above

  • No anemic domain models
  • No dependency injection of services into entities

Possible approaches

  • Factories
  • Double dispatch (can this be used for identity generation?)
  • Generation inside repositiories
  • Generation inside infrastructure (e.g. ORM or database)
  • Injection services into entities

回答1:


I would place it in a factory. Generating id shouldn't be a part of domain logic in my opinion, because it's really an infrastructure matter. You can take id from DB or generate it with uuid or whatever. It's a detail. Also remember that only interface of a factory belongs to domain layer, not its implementation.

About your doubts for factory, if you use factory to create entities then you should use it everywhere. This is how I do it.




回答2:


Vaughn Vernon author of Implementing Domain Driven Design advocates creating unique ids in repositories like this:

   public TenantId nextIdentity() {
        return new TenantId(UUID.randomUUID().toString().toUpperCase());
    }

TenantId is a value object that wraps the identity of the Entity.



来源:https://stackoverflow.com/questions/25742703/generating-identities-for-entities-in-ddd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!