Transactions in the Repository Pattern

后端 未结 6 880
小鲜肉
小鲜肉 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:37

    Using Spring.NET AOP + NHibernate you can write your repository class as normal and configure your transactions in custom XML file:

    public class CustomerService : ICustomerService
    {
        private readonly ICustomerRepository _customerRepository;
        private readonly IOrderRepository _orderRepository;
    
        public CustomerService(
            ICustomerRepository customerRepository, 
            IOrderRepository orderRepository) 
        {
            _customerRepository = customerRepository;
            _orderRepository = orderRepository;
        }
    
        public int CreateOrder(Order o, Customer c) 
        {
            // Do something with _customerRepository and _orderRepository
        }
    }
    

    In the XML file you select which methods you would like to be executed inside a transaction:

      
    
        
    
        
          
            
          
        
      
    
      
        
          
              
              
          
        
    
      
    

    And in your code you obtain an instance of the CustomerService class like this:

    ICustomerService customerService = (ICustomerService)ContextRegistry
        .GetContent()
        .GetObject("customerService");
    

    Spring.NET will return you a proxy of the CustomerService class that will apply a transaction when you call CreateOrder method. This way there's no transaction specific code inside your service classes. AOP takes care of it. For more details you can take a look at the documentation of Spring.NET.

提交回复
热议问题