Who's responsibility is to generate the Identity for the Entity. Is it the domain or the repository?
The identity of an entity can be assigned by the domain either directly or via client request. This type of identity is usually generated with a Guid
or another universally unique value. The identity can also be assigned by the repository to reflect a database generated identity such as an incremental identity column.
How the syncing of identities can be done between the repositories and the domain?
When an entity's identity is sourced from a database generated identity column, the domain should not assign its own identity. A transient entity with an integral identity will initially have identity value 0. When the transient entity is made persistent, the repository will assign the identity value. At that point, as you point out, there may some issues with cached instances of the newly persistent entity instance since the identity value has changed. There are a few ways to resolve these issues, but I try to avoid referencing transient entities in caches (or anywhere else) in the first places. This can be more easily done by making sure an entity isn't referenced in many places until it is made persistent. If you do end up referencing a transient entity instance in various places, you can make sure that its .NET runtime identity remains the same for the lifetime of the instance. To do this, you have to compare entities via object.ReferenceEquals
before the identity value check and you have to cache the hash-code generated via GetHashCode
for the duration of the object lifetime.