public interface IUnitOfWork
{
void Save();
}
Assuming we plan to only ever switch between different O/RMs ( access to these O/RMs is encapsulated using Repository pattern ), which already provide their own implementations of a Unit of Work pattern, are there any reasons why we shouldn’t use TransactionScope approach instead of IUnitOfWork?
Thank you
The implementation of your IUnitOfWork can use whatever technological means of “transactionalizing” the changes between different aggregates at one time that you wish, be it TransactionScope, SqlTransaction, or whatever means you choose to use. This does not negate the need for IUnitOfWork though.
Repositories are designed for a specific aggregate. If you are only persisting changes to a single aggregate type at a time, then you may use only the repository. But, if you are persisting different aggregates at the same time and need that persistence to be “transactionalized” so that the changes are persisted all or nothing, then this is where the Unit of Work pattern comes into play.
Per your example, we’ll say you are using Linq as your OR/M and you’re persisting your aggregates to a SQL data store, but want to wrap the persistence into a TransactionScope. You may have an IUnitOfWork definition like so:
Then, your implementation may be like this:
The main idea here is that TransactionScope is one way of implementing IUnitOfWork, but having the Unit of Work contract allows you to provide different implementations based on your environment.
Hope this helps!