0
public interface IUnitOfWork
{        
    void Save();
}

假设我们计划只在不同的 O/RM 之间切换(对这些 O/RM 的访问是使用 Repository 模式封装的),它们已经提供了自己的工作单元模式的实现,有什么理由不应该使用TransactionScope方法而不是IUnitOfWork

谢谢

4

2 回答 2

2

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:

public interface IUnitOfWork 
{
  void MarkDirty(IAggregateRoot entity);
  void MarkNew(IAggregateRoot entity);
  void MarkDeleted(IAggregateRoot entity);
  void Commit();
  void Rollback();
}

Then, your implementation may be like this:

public LinqTransactionScopeUnitOfWork : IUnitOfWork
{
    public void Commit()
    {
        using (TransactionScope scope = new TransactionScope())
        {
            foreach (IAggregateRoot root in Changes)
            {
                //Save root based on how it was marked and what it's concrete type is using Linq.
            }

            scope.Complete();
        }
    }
}

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!

于 2013-01-07T22:51:38.473 回答
1

There is one technical reason : you might have difficulties using TransactionScope in your environment, you need to start a service & unlock firewall port. I you don't have these problems I'd suggest you to use TransactionScope : it's already done / debugged, why would you think you'd do something better ?

于 2013-01-08T10:21:20.807 回答