Skip to content

Instantly share code, notes, and snippets.

@holmberd
Last active May 26, 2024 23:06
Show Gist options
  • Save holmberd/1feb59594252ae68c70d2f0a2401f825 to your computer and use it in GitHub Desktop.
Save holmberd/1feb59594252ae68c70d2f0a2401f825 to your computer and use it in GitHub Desktop.
Unit Of Work

Context

Aggregate is a pattern in Domain-Driven Design. A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An example may be an order and its line-items, these will be separate objects, but it's useful to treat the order (together with its line items) as a single aggregate.

An aggregate will have one of its component objects be the aggregate root. Any references from outside the aggregate should only go to the aggregate root. The root can thus ensure the integrity of the aggregate as a whole.

Aggregates are the basic element of transfer of data storage - you request to load or save whole aggregates. Transactions should not cross aggregate boundaries.

Source: https://martinfowler.com/bliki/DDD_Aggregate.html

Leave transaction control to the client. Although the REPOSITORY will insert into and delete from the database, it will ordinarily not commit anything. It is tempting to commit after saving, for example, but the client presumably has the context to correctly initiate and commit units of work. Transaction management will be simpler if the REPOSITORY keeps its hands off.

Source [Eric Evans, DDD Book, CH 6, Repositories]

Unit of Work

The Unit of Work pattern is primarily used for tracking and managing changes to aggregates, ensuring that all changes within a unit of work are committed as a single transaction. In the context of DDD, it is generally used to manage changes to multiple instances of the same aggregate type within a single transaction, adhering to the rule that transactions should not cross aggregate boundaries.

Example: An Order aggregate which has many OrderItems. If we need to create multiple orders within the same business transaction, we can use a Unit of Work to commit all those orders within the same transaction when we commit the Unit of Work. The Client can control when we start the transaction, otherwise it is deferred until we commit the unit of work.

Change Tracking

The Change Tracking pattern is primarily used for tracking changes made within an aggregate to efficiently persist modifications.

Example: An Order aggregate which has many OrderItems. If we need to insert, update, and delete OrderItems and keep track of what has changed within the Order aggregate when saving the aggregate.

Comments

Both patterns are technically a form of change tracking, but operates at different levels on our aggregates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment