New entity ID in domain event -


i'm building application domain model using cqrs , domain events concepts (but no event sourcing, plain old sql). there no problem events of somethingchanged kind. got stuck in implementing somethingcreated events.

when create entity mapped table identity primary key don't know id until entity persisted. entity persistence ignorant when publishing event inside entity, id not known - it's magically set after calling context.savechanges() only. how/where/when can put id in event data?

i thinking of:

  • including reference entity in event. work inside domain not necesarily in distributed environment multiple autonomous system communicating events/messages.
  • overriding savechanges() somehow update events enqueued publishing. events meant immutable, seems dirty.
  • getting rid of identity fields , using guids generated in entity constructor. might easiest hit performance , make other things harder, debugging or querying (where id = 'b85e62c3-dc56-40c0-852a-49f759ac68fb', no min, max etc.). that's see in many sample applications.
  • hybrid approach - leave alone identity , use foreign keys , faster joins use guid unique identifier pull entities repository in application.

personally guids unique identifiers, in multi-user, distributed environments numeric ids cause problems. such, never use database generated identity columns/properties , problem goes away.

short of that, since following cqrs, undoubtedly have createsomethingcommand , corresponding createsomethingcommandhandler carries out steps required create new instance , persist new object using repository (via context.savechanges). raise somethingcreated event here rather in domain object itself.

for one, solves problem because command handler can wait database operation complete, pull out identity value, update object pass identity in event. but, more importantly, addresses tricky question of when object 'created'?

raising domain event in constructor bad practice constructors should lean , perform initialization. plus, in model, object isn't created until has id assigned. means there additional initialization steps required after constructor has executed. if have more 1 step, enforce order of execution (another anti-pattern) or put check in each recognize when done (ooh, smelly)? can see how can spiral out of hand.

so, recommendation raise event command handler. (note: if switch guid identifiers, i'd follow approach because should never raise events constructors.)


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -