Transactions in the Repository Pattern

后端 未结 6 886
小鲜肉
小鲜肉 2020-12-12 18:07

How do I encapsulate the saving of more than one entity in a transactional manner using the repository pattern? For example, what if I wanted to add an order and update the

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 18:36

    I would look at using some type of Transaction Scope / Context system. So you might have the following code which is roughly based on .Net & C#.

    public class OrderService
    {
    
    public void CreateNewOrder(Order order, Customer customer)
    {
      //Set up our transactional boundary.
      using (TransactionScope ts=new TransactionScope())
      {
        IOrderRepository orderRepos=GetOrderRespository();
        orderRepos.SaveNew(order);
        customer.Status=CustomerStatus.OrderPlaced;
    
        ICustomerRepository customerRepository=GetCustomerRepository();
        customerRepository.Save(customer)
        ts.Commit();   
       }
    }
    }
    

    TransactionScope can nest so let's say you had an action which crossed multiple services your application would create a TransactionScope as well. Now in the current .net if you use the TransactionScope they have you risk escallating to a DTC but this will be resolved in the future.

    We had created our own TransactionScope class which basically managed our DB connections and used local SQL transactions.

提交回复
热议问题