Where should I set fields like CreatedDate, CreatedBy, ModifiedDate, ModifiedBy? Should I pass current user context to repository and set it there or maybe better way is to set it in application service (but then it must be done in each API method rather than only in Add/Update in repository)?
It depends on your domain.
If values like CreatedDate
, CreatedBy
... are for tracking or logging purpose, then I'd place them in the Infrastructure
(Repository).
On the other hand, if these values belong to my domain for any reason, then I'd place them in the domain layer.
Example: imaging that in a Banking Transfer context, a customer could cancel a transfer only until 24 hours after submit it for settlement. Then the domain needs CreateTransferDate
to satisfy the invariants.
Another option could be a listener that consume all domain events and save historial time data of what happen.
CreatedDate, CreatedBy, ModifiedDate and ModifiedBy are typically concepts that have no real domain value, but they are more like a technical concept; and that's why I typically don't set these in application or domain layer, but in repository layer. After all, the repository layer is a technical layer. In a domain I don't care about this kind of information. Unless of course, it's part of the ubiquitous language, but mostly it's not.
Also, if ModifiedDate would be part of the domain/application, you would have to set it with each manipulation you do, which would be very tedious and error-prone. If you do it in the repository, it's easier, because you do it with every update.
So I would ask the question: does business care about it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With