how to implement Unit Of Work just using just Tran

2019-06-05 20:14发布

I am working on a existing system(asp.net 2, ms sql server 2005) where repository pattern is implemented like:

IMyRepository
{
  void add(object o);
  int update(object obj);
  int delete(object obj);
  IList<T> getAll();
  IList<T> getByDate(DateTime date);
....
}

The system has 3 different products. So We have different repository for each product. As the requirement changes over time, we need to implement Unit Of Work pattern for business process level transaction.
We don't have any ORM.(actually we don't have the permission or time to implement it now) Can anyone give me a clear guideline how to implement Unit Of Work just using just TransactionScope and sqlconnections.

Plz mention how to close Sqlconnections quickly and efficiently(as it has large number of users).
The unit of work pattern is new thing to me.
thanks in advance ...

1条回答
\"骚年 ilove
2楼-- · 2019-06-05 20:30

Well, in your unit of work pattern you have a call to Commit() and/or Rollback(). With TransactionScope, you call Complete() or nothing at all, which does the rollback.

using(TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
{
  // do your gets inside of supressed TransactionScopes:
  using (new TransactionScope(TransactionScopeOption.Suppress))
  {
    myRep.GetAll();
  }

  // do your updates
  myRep.Update();

  // no errors, so commit
  ts.Complete();

  // Close db connections
  myConn.Close();
}

Surround the whole thing with a try catch and you'll be all setup. If you get any exceptions, ts.Complete() is never called and your db changes are rolled back. Just remember to reset your connections before you start the transactionscope, and right after you commit or rollback.

查看更多
登录 后发表回答