I have been studying DDD for 1.5 weeks now, and I came a cross the use of the Unit Of Work pattern together with Data Mapper pattern. I understood why they are both important and when to use them but, I couldn’t find anywhere how the Data Mapper can “know” that a save method, for example, was called in the middle of a transaction or not. Is there something wrong with the Data Mapper being aware of the Unit of Work? Something tells me that is not the right way to go.
The boundary for a Unit of Work is time. It answers the question: What all are we changing in this one transaction?
The boundary for a Data Mapper is space. It answers the question: What all is part of this one data structure?
The unit of work is used to prevent hitting the database too often by sending every little chunk of info one at a time. The data mapper translates the structure of those little chunks in memory to the structure of those little chunks on disk, and vise versa.
These don’t need to know about each other. A single unit of work may involve many data mappers. A single data mapper may involve many units of work. The two are orthogonal to each other.
2
The data mapper has to know about the unit of work. You would typically pass the UoW to the mapper using DI.
I understood why they are both important and when to use them but, I couldn’t find anywhere how the Data Mapper can “know” that a save method, for example, was called in the middle of a transaction or not.
A single UoW instance represents one active business transaction, the fact that the mapper has a valid UoW instance implies that you are in a business transaction and things are not committed yet; also whether the transaction is committed or not is of no concern to the mapper. UoW lifetime management happens at a higher level (E.g for a web app it is usually UoW er request).
2